Uploading file from android (java) to server using PHP - java

Hello Im trying to upload files from my android application to my server using PHP.
I have read this posts:
How to upload a file using Java HttpClient library working with PHP
http://www.veereshr.com/Java/Upload
How do I send a file in Android from a mobile device to server using http?
This is my JAVA code:
public void upload() throws Exception {
File file = new File("data/data/com.tigo/databases/exercise");
Log.i("file.getName()", file.getName());
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://***.***.***.***/backDatabase.php");
InputStreamEntity reqEntity = new InputStreamEntity( new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
if((response.getStatusLine().toString()).equals("HTTP/1.1 200 OK")){
// Successfully Uploaded
Log.i("uploaded", response.getStatusLine().toString());
}
else{
// Did not upload. Add your logic here. Maybe you want to retry.
Log.i(" not uploaded", response.getStatusLine().toString());
}
httpclient.getConnectionManager().shutdown();
}
This is my PHP code:
<?php
$uploads_dir = '/tigo/databaseBackup';
if (is_uploaded_file($_FILES['exercise']['tmp_name']))
{
$info = "File ". $_FILES['exercise']['name'] ." uploaded successfully.\n";
$file = 'emailTest.log';
file_put_contents($file, $info, FILE_APPEND | LOCK_EX);
move_uploaded_file ($_FILES['exercise'] ['tmp_name'], $_FILES['exercise'] ['name']);
}
else
{
$info = "Possible file upload attack: ";
$file = 'emailTest.log';
file_put_contents($file, $info, FILE_APPEND | LOCK_EX);
$info = "filename '". $_FILES['exercise']['tmp_name'] . "'.";
file_put_contents($file, $info, FILE_APPEND | LOCK_EX);
print_r($_FILES);
}
?>
In my logcat i get HTTP/1.1 200 OK.
When i look at the server logs i get this error:
PHP Notice: Undefined index: exercise in /var/www/backDatabase.php on line 23
I also tried to use:
$_FILES['userfile']['name']
Instead of
$_FILES['exercise']['tmp_name']
And i got the same error in my server logs.
I think my problem is that I cant get reference to my uploaded file.
Thanks for helping.

try multipart entity
public void upload(String filepath) throws IOException
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("url");
File file = new File(filepath);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
// check the response and do what is required
}

Try this:
JAVA code:
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
public class UploadFile {
public static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("http://***.***.***.***/backDatabase.php");
File file = new File("/data/data/com.tigo/databases/exercise");
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
}
}
PHP code:
<?php
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n";
move_uploaded_file ($_FILES['userfile'] ['tmp_name'], $_FILES['userfile'] ['name']);
} else {
echo "Possible file upload attack: ";
echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
print_r($_FILES); }
?>
You may need to change the paths in order to fit your needs, but the above code works.

Upload Image on Web Server using Android / C# {Xamarin}
This is Just Small Piece of Code. it can send any image from Android to your Web
Server using Android
System.Net.WebClient Client = new System.Net.WebClient();
Client.Headers.Add("Content-Type", "binary/octet-stream");
byte[] result = Client.UploadFile("localhost/FolderName/upload.php", "POST", path);
string s = System.Text.Encoding.UTF8.GetString(result, 0, result.Length);
Here is the PHP Code {upload.php}. Create a Folder name { Uploads } in
your Application.
<?php
$uploads_dir = 'uploads/'; //Directory to save the file that comes from client application.
if ($_FILES["file"]["error"] == UPLOAD_ERR_OK)
{
$tmp_name = $_FILES["file"]["tmp_name"];
$name = $_FILES["file"]["name"];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
?>

Related

How to convert this cUrl command to java containing form and binary data [duplicate]

In the days of version 3.x of Apache Commons HttpClient, making a multipart/form-data POST request was possible (an example from 2004). Unfortunately this is no longer possible in version 4.0 of HttpClient.
For our core activity "HTTP", multipart is somewhat
out of scope. We'd love to use multipart code maintained by some
other project for which it is in scope, but I'm not aware of any.
We tried to move the multipart code to commons-codec a few years
ago, but I didn't take off there. Oleg recently mentioned another
project that has multipart parsing code and might be interested
in our multipart formatting code. I don't know the current status
on that. (http://www.nabble.com/multipart-form-data-in-4.0-td14224819.html)
Is anybody aware of any Java library that allows me to write an HTTP client that can make a multipart/form-data POST request?
Background: I want to use the Remote API of Zoho Writer.
We use HttpClient 4.x to make multipart file post.
UPDATE: As of HttpClient 4.3, some classes have been deprecated. Here is the code with new API:
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost("...");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN);
// This attaches the file to the POST:
File f = new File("[/path/to/upload]");
builder.addBinaryBody(
"file",
new FileInputStream(f),
ContentType.APPLICATION_OCTET_STREAM,
f.getName()
);
HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
CloseableHttpResponse response = httpClient.execute(uploadFile);
HttpEntity responseEntity = response.getEntity();
Below is the original snippet of code with deprecated HttpClient 4.0 API:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
FileBody bin = new FileBody(new File(fileName));
StringBody comment = new StringBody("Filename: " + fileName);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("bin", bin);
reqEntity.addPart("comment", comment);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
These are the Maven dependencies I have.
Java Code:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
FileBody uploadFilePart = new FileBody(uploadFile);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("upload-file", uploadFilePart);
httpPost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httpPost);
Maven Dependencies in pom.xml:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.0.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.0.1</version>
<scope>compile</scope>
</dependency>
If size of the JARs matters (e.g. in case of applet), one can also directly use httpmime with java.net.HttpURLConnection instead of HttpClient.
httpclient-4.2.4: 423KB
httpmime-4.2.4: 26KB
httpcore-4.2.4: 222KB
commons-codec-1.6: 228KB
commons-logging-1.1.1: 60KB
Sum: 959KB
httpmime-4.2.4: 26KB
httpcore-4.2.4: 222KB
Sum: 248KB
Code:
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
FileBody fileBody = new FileBody(new File(fileName));
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);
multipartEntity.addPart("file", fileBody);
connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue());
OutputStream out = connection.getOutputStream();
try {
multipartEntity.writeTo(out);
} finally {
out.close();
}
int status = connection.getResponseCode();
...
Dependency in pom.xml:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.2.4</version>
</dependency>
Use this code to upload images or any other files to the server using post in multipart.
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
public class SimplePostRequestTest {
public static void main(String[] args) throws UnsupportedEncodingException, IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.102/uploadtest/upload_photo");
try {
FileBody bin = new FileBody(new File("/home/ubuntu/cd.png"));
StringBody id = new StringBody("3");
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("upload_image", bin);
reqEntity.addPart("id", id);
reqEntity.addPart("image_title", new StringBody("CoolPic"));
httppost.setEntity(reqEntity);
System.out.println("Requesting : " + httppost.getRequestLine());
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost, responseHandler);
System.out.println("responseBody : " + responseBody);
} catch (ClientProtocolException e) {
} finally {
httpclient.getConnectionManager().shutdown();
}
}
}
it requires below files to upload.
libraries are
httpclient-4.1.2.jar,
httpcore-4.1.2.jar,
httpmime-4.1.2.jar,
httpclient-cache-4.1.2.jar,
commons-codec.jar and
commons-logging-1.1.1.jar to be in classpath.
Here's a solution that does not require any libraries.
This routine transmits every file in the directory d:/data/mpf10 to urlToConnect
String boundary = Long.toHexString(System.currentTimeMillis());
URLConnection connection = new URL(urlToConnect).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
PrintWriter writer = null;
try {
writer = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
File dir = new File("d:/data/mpf10");
for (File file : dir.listFiles()) {
if (file.isDirectory()) {
continue;
}
writer.println("--" + boundary);
writer.println("Content-Disposition: form-data; name=\"" + file.getName() + "\"; filename=\"" + file.getName() + "\"");
writer.println("Content-Type: text/plain; charset=UTF-8");
writer.println();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
writer.println(line);
}
} finally {
if (reader != null) {
reader.close();
}
}
}
writer.println("--" + boundary + "--");
} finally {
if (writer != null) writer.close();
}
// Connection is lazily executed whenever you request any status.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
// Handle response
You can also use REST Assured which builds on HTTP Client. It's very simple:
given().multiPart(new File("/somedir/file.bin")).when().post("/fileUpload");
httpcomponents-client-4.0.1 worked for me. However, I had to add the external jar apache-mime4j-0.6.jar (org.apache.james.mime4j) otherwise
reqEntity.addPart("bin", bin); would not compile. Now it's working like charm.
I found this sample in Apache's Quickstart Guide. It's for version 4.5:
/**
* Example how to use multipart/form encoded POST request.
*/
public class ClientMultipartFormPost {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("File path not given");
System.exit(1);
}
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("http://localhost:8080" +
"/servlets-examples/servlet/RequestInfoExample");
FileBody bin = new FileBody(new File(args[0]));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("bin", bin)
.addPart("comment", comment)
.build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}
You will happy!
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.1</version>
</dependency>
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ByteArrayBody;
byte[] byteArr1 = multipartFile1.getBytes();
byte[] byteArr2 = multipartFile2.getBytes();
HttpEntity reqEntity = MultipartEntityBuilder.create().setCharset(Charset.forName("UTF-8"))
.addPart("image1", new ByteArrayBody(byteArr1, req.getMultipartFile1().getOriginalFilename()))
.addPart("image2", new ByteArrayBody(byteArr2, req.getMultipartFile2().getOriginalFilename()))
.build();
We have a pure java implementation of multipart-form submit without using any external dependencies or libraries outside jdk. Refer https://github.com/atulsm/https-multipart-purejava/blob/master/src/main/java/com/atul/MultipartPure.java
private static String body = "{\"key1\":\"val1\", \"key2\":\"val2\"}";
private static String subdata1 = "## -2,3 +2,4 ##\r\n";
private static String subdata2 = "<data>subdata2</data>";
public static void main(String[] args) throws Exception{
String url = "https://" + ip + ":" + port + "/dataupload";
String token = "Basic "+ Base64.getEncoder().encodeToString((userName+":"+password).getBytes());
MultipartBuilder multipart = new MultipartBuilder(url,token);
multipart.addFormField("entity", "main", "application/json",body);
multipart.addFormField("attachment", "subdata1", "application/octet-stream",subdata1);
multipart.addFormField("attachment", "subdata2", "application/octet-stream",subdata2);
List<String> response = multipart.finish();
for (String line : response) {
System.out.println(line);
}
}
My code post multipartFile to server.
public static HttpResponse doPost(
String host,
String path,
String method,
MultipartFile multipartFile
) throws IOException
{
HttpClient httpClient = wrapClient(host);
HttpPost httpPost = new HttpPost(buildUrl(host, path));
if (multipartFile != null) {
HttpEntity httpEntity;
ContentBody contentBody;
contentBody = new ByteArrayBody(multipartFile.getBytes(), multipartFile.getOriginalFilename());
httpEntity = MultipartEntityBuilder.create()
.addPart("nameOfMultipartFile", contentBody)
.build();
httpPost.setEntity(httpEntity);
}
return httpClient.execute(httpPost);
}
My code for sending files to server using post in multipart.
Make use of multivalue map while making request for sending form data
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("FILE", new FileSystemResource(file));
map.add("APPLICATION_ID", Number);
httpService.post( map,headers);
At receiver end use
#RequestMapping(value = "fileUpload", method = RequestMethod.POST)
public ApiResponse AreaCsv(#RequestParam("FILE") MultipartFile file,#RequestHeader("clientId") ){
//code
}
Using HttpRequestFactory to jira xray's /rest/raven/1.0/import/execution/cucumber/multipart :
Map<String, Object> params = new HashMap<>();
params.put( "info", "zigouzi" );
params.put( "result", "baalo" );
HttpContent content = new UrlEncodedContent(params);
OAuthParameters oAuthParameters = jiraOAuthFactory.getParametersForRequest(ACCESS_TOKEN, CONSUMER_KEY, PRIVATE_KEY);
HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory(oAuthParameters);
HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(url), content);
request.getHeaders().setAccept("application/json");
String boundary = Long.toHexString(System.currentTimeMillis());
request.getHeaders().setContentType("multipart/form-data; boundary="+boundary);
request.getHeaders().setContentEncoding("application/json");
HttpResponse response = null ;
try
{
response = request.execute();
Scanner s = new Scanner(response.getContent()).useDelimiter("\\A");
result = s.hasNext() ? s.next() : "";
}
catch (Exception e)
{
}
did the trick.

Send an image from Google Glass to a HTTP server [duplicate]

In the days of version 3.x of Apache Commons HttpClient, making a multipart/form-data POST request was possible (an example from 2004). Unfortunately this is no longer possible in version 4.0 of HttpClient.
For our core activity "HTTP", multipart is somewhat
out of scope. We'd love to use multipart code maintained by some
other project for which it is in scope, but I'm not aware of any.
We tried to move the multipart code to commons-codec a few years
ago, but I didn't take off there. Oleg recently mentioned another
project that has multipart parsing code and might be interested
in our multipart formatting code. I don't know the current status
on that. (http://www.nabble.com/multipart-form-data-in-4.0-td14224819.html)
Is anybody aware of any Java library that allows me to write an HTTP client that can make a multipart/form-data POST request?
Background: I want to use the Remote API of Zoho Writer.
We use HttpClient 4.x to make multipart file post.
UPDATE: As of HttpClient 4.3, some classes have been deprecated. Here is the code with new API:
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost("...");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN);
// This attaches the file to the POST:
File f = new File("[/path/to/upload]");
builder.addBinaryBody(
"file",
new FileInputStream(f),
ContentType.APPLICATION_OCTET_STREAM,
f.getName()
);
HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
CloseableHttpResponse response = httpClient.execute(uploadFile);
HttpEntity responseEntity = response.getEntity();
Below is the original snippet of code with deprecated HttpClient 4.0 API:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
FileBody bin = new FileBody(new File(fileName));
StringBody comment = new StringBody("Filename: " + fileName);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("bin", bin);
reqEntity.addPart("comment", comment);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
These are the Maven dependencies I have.
Java Code:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
FileBody uploadFilePart = new FileBody(uploadFile);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("upload-file", uploadFilePart);
httpPost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httpPost);
Maven Dependencies in pom.xml:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.0.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.0.1</version>
<scope>compile</scope>
</dependency>
If size of the JARs matters (e.g. in case of applet), one can also directly use httpmime with java.net.HttpURLConnection instead of HttpClient.
httpclient-4.2.4: 423KB
httpmime-4.2.4: 26KB
httpcore-4.2.4: 222KB
commons-codec-1.6: 228KB
commons-logging-1.1.1: 60KB
Sum: 959KB
httpmime-4.2.4: 26KB
httpcore-4.2.4: 222KB
Sum: 248KB
Code:
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
FileBody fileBody = new FileBody(new File(fileName));
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);
multipartEntity.addPart("file", fileBody);
connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue());
OutputStream out = connection.getOutputStream();
try {
multipartEntity.writeTo(out);
} finally {
out.close();
}
int status = connection.getResponseCode();
...
Dependency in pom.xml:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.2.4</version>
</dependency>
Use this code to upload images or any other files to the server using post in multipart.
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
public class SimplePostRequestTest {
public static void main(String[] args) throws UnsupportedEncodingException, IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.102/uploadtest/upload_photo");
try {
FileBody bin = new FileBody(new File("/home/ubuntu/cd.png"));
StringBody id = new StringBody("3");
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("upload_image", bin);
reqEntity.addPart("id", id);
reqEntity.addPart("image_title", new StringBody("CoolPic"));
httppost.setEntity(reqEntity);
System.out.println("Requesting : " + httppost.getRequestLine());
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost, responseHandler);
System.out.println("responseBody : " + responseBody);
} catch (ClientProtocolException e) {
} finally {
httpclient.getConnectionManager().shutdown();
}
}
}
it requires below files to upload.
libraries are
httpclient-4.1.2.jar,
httpcore-4.1.2.jar,
httpmime-4.1.2.jar,
httpclient-cache-4.1.2.jar,
commons-codec.jar and
commons-logging-1.1.1.jar to be in classpath.
Here's a solution that does not require any libraries.
This routine transmits every file in the directory d:/data/mpf10 to urlToConnect
String boundary = Long.toHexString(System.currentTimeMillis());
URLConnection connection = new URL(urlToConnect).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
PrintWriter writer = null;
try {
writer = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
File dir = new File("d:/data/mpf10");
for (File file : dir.listFiles()) {
if (file.isDirectory()) {
continue;
}
writer.println("--" + boundary);
writer.println("Content-Disposition: form-data; name=\"" + file.getName() + "\"; filename=\"" + file.getName() + "\"");
writer.println("Content-Type: text/plain; charset=UTF-8");
writer.println();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
writer.println(line);
}
} finally {
if (reader != null) {
reader.close();
}
}
}
writer.println("--" + boundary + "--");
} finally {
if (writer != null) writer.close();
}
// Connection is lazily executed whenever you request any status.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
// Handle response
You can also use REST Assured which builds on HTTP Client. It's very simple:
given().multiPart(new File("/somedir/file.bin")).when().post("/fileUpload");
httpcomponents-client-4.0.1 worked for me. However, I had to add the external jar apache-mime4j-0.6.jar (org.apache.james.mime4j) otherwise
reqEntity.addPart("bin", bin); would not compile. Now it's working like charm.
I found this sample in Apache's Quickstart Guide. It's for version 4.5:
/**
* Example how to use multipart/form encoded POST request.
*/
public class ClientMultipartFormPost {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("File path not given");
System.exit(1);
}
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("http://localhost:8080" +
"/servlets-examples/servlet/RequestInfoExample");
FileBody bin = new FileBody(new File(args[0]));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("bin", bin)
.addPart("comment", comment)
.build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}
You will happy!
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.1</version>
</dependency>
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ByteArrayBody;
byte[] byteArr1 = multipartFile1.getBytes();
byte[] byteArr2 = multipartFile2.getBytes();
HttpEntity reqEntity = MultipartEntityBuilder.create().setCharset(Charset.forName("UTF-8"))
.addPart("image1", new ByteArrayBody(byteArr1, req.getMultipartFile1().getOriginalFilename()))
.addPart("image2", new ByteArrayBody(byteArr2, req.getMultipartFile2().getOriginalFilename()))
.build();
We have a pure java implementation of multipart-form submit without using any external dependencies or libraries outside jdk. Refer https://github.com/atulsm/https-multipart-purejava/blob/master/src/main/java/com/atul/MultipartPure.java
private static String body = "{\"key1\":\"val1\", \"key2\":\"val2\"}";
private static String subdata1 = "## -2,3 +2,4 ##\r\n";
private static String subdata2 = "<data>subdata2</data>";
public static void main(String[] args) throws Exception{
String url = "https://" + ip + ":" + port + "/dataupload";
String token = "Basic "+ Base64.getEncoder().encodeToString((userName+":"+password).getBytes());
MultipartBuilder multipart = new MultipartBuilder(url,token);
multipart.addFormField("entity", "main", "application/json",body);
multipart.addFormField("attachment", "subdata1", "application/octet-stream",subdata1);
multipart.addFormField("attachment", "subdata2", "application/octet-stream",subdata2);
List<String> response = multipart.finish();
for (String line : response) {
System.out.println(line);
}
}
My code post multipartFile to server.
public static HttpResponse doPost(
String host,
String path,
String method,
MultipartFile multipartFile
) throws IOException
{
HttpClient httpClient = wrapClient(host);
HttpPost httpPost = new HttpPost(buildUrl(host, path));
if (multipartFile != null) {
HttpEntity httpEntity;
ContentBody contentBody;
contentBody = new ByteArrayBody(multipartFile.getBytes(), multipartFile.getOriginalFilename());
httpEntity = MultipartEntityBuilder.create()
.addPart("nameOfMultipartFile", contentBody)
.build();
httpPost.setEntity(httpEntity);
}
return httpClient.execute(httpPost);
}
My code for sending files to server using post in multipart.
Make use of multivalue map while making request for sending form data
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("FILE", new FileSystemResource(file));
map.add("APPLICATION_ID", Number);
httpService.post( map,headers);
At receiver end use
#RequestMapping(value = "fileUpload", method = RequestMethod.POST)
public ApiResponse AreaCsv(#RequestParam("FILE") MultipartFile file,#RequestHeader("clientId") ){
//code
}
Using HttpRequestFactory to jira xray's /rest/raven/1.0/import/execution/cucumber/multipart :
Map<String, Object> params = new HashMap<>();
params.put( "info", "zigouzi" );
params.put( "result", "baalo" );
HttpContent content = new UrlEncodedContent(params);
OAuthParameters oAuthParameters = jiraOAuthFactory.getParametersForRequest(ACCESS_TOKEN, CONSUMER_KEY, PRIVATE_KEY);
HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory(oAuthParameters);
HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(url), content);
request.getHeaders().setAccept("application/json");
String boundary = Long.toHexString(System.currentTimeMillis());
request.getHeaders().setContentType("multipart/form-data; boundary="+boundary);
request.getHeaders().setContentEncoding("application/json");
HttpResponse response = null ;
try
{
response = request.execute();
Scanner s = new Scanner(response.getContent()).useDelimiter("\\A");
result = s.hasNext() ? s.next() : "";
}
catch (Exception e)
{
}
did the trick.

How to retrieve file contents to upload in API? Solved

I'm stuck in a problem of trying to upload something with a File parameter...
I had the idea of acquiring the string of the file, but I realized that I need to acquire the file's contents. How do you retrieve the file contents and upload it to the designated site?
EDIT: Managed to find problem
Here's the solution:
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("https://api.teknik.io/upload/post");
FileBody bin = new FileBody(new File("C:/Users/hp/Desktop/hid.txt"));
HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", bin).build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
System.out.println(EntityUtils.toString(resEntity));
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
It returns:
HTTP/1.1 200 OK
Response content length: 119
[{"results":
{"file":{"name":"rB8mlB.txt","url":"https://u.teknik.io/rB8mlB.txt","type":"inode/x-empty","size":0}}}]
I managed to make it work on a pdf file, but txt files are problematic
HTTP/1.1 200 OK
Response content length: 126
[{"results":{"file":{"name":"RfWjkg.pdf","url":"https://u.teknik.io/RfWjkg.pdf","type":"application/pdf","size":341852}}}]
use MultipartRequest jar file.
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
import java.util.*;
import com.oreilly.servlet.*;
public class UploadServlet extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse res) throws IOException , ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
MultipartRequest mpr=new MultipartRequest(req,getServletContext().getRealPath("file"),500*1024*1024);
out.println("<html><body><h3>File Uploaded<h3></html></body>");
}
}
call this servlet on upload button.

Uploading a small sized image to server using php and android

On PHP Side I am using following Code
$val = (isset($_GET['file']) ? $_GET['file'] : null);
$isUploaded = false;
return $val;
if($val != null)
{
if (move_uploaded_file(#$_FILES['file']['tmp_name'], $mainPath))
{
$isUploaded = true;
}
}
Android side I am using
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("file", Base64Coder.encodeLines(imageArray)));
HttpResponse response = null;
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter("http.connection-manager.timeout", 15000);
try {
HttpPost httppost = new HttpPost(url);
httppost.setEntity(entity);
response = httpclient.execute(httppost);
However
$val = (isset($_GET['file']) ? $_GET['file'] : null);
returns null
How can I upload image properly
This is my code for upload, and it's work. You need import httpmime jar
PHP code
$uploads_dir = '/Library/WebServer/Documents/Upload/upload/'.$_FILES['userfile']['name'];
if(is_uploaded_file($_FILES['userfile']['tmp_name'])) {
echo $_POST["contentString"]."\n";
echo "File path = ".$uploads_dir;
move_uploaded_file ($_FILES['userfile'] ['tmp_name'], $uploads_dir);
} else {
echo "\n Upload Error";
echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
print_r($_FILES);
JAVA code
HttpClient client = new DefaultHttpClient();
HttpPost postMethod = new HttpPost("http://localhost/Upload/index.php");
File file = new File(filePath);
MultipartEntity entity = new MultipartEntity();
FileBody contentFile = new FileBody(file);
entity.addPart("userfile",contentFile);
StringBody contentString = new StringBody("This is contentString");
entity.addPart("contentString",contentString);
postMethod.setEntity(entity);
HttpResponse response = client.execute(postMethod);
HttpEntity httpEntity = response.getEntity();
String state = EntityUtils.toString(httpEntity);
$val = (isset($_GET['file']) ? $_GET['file'] : null);
Replace with
$val = (isset($_FILES['file']['name']) ? $_FILES['file']['name'] : null);
Check manual for available fields for post method uploads.
http://www.php.net/manual/en/features.file-upload.post-method.php

HTTP 403 Service Error when trying to post XML to HTTPS URL

I am trying to write a small class using the Apache HttpClient library that would do an HTTPS post to a specified URL sending some XML. When I run my code, the HTTP status line I receive back is "403 Service Error". Here's the complete error HTML returned:
$errorDump java.net.SocketTimeoutException:Read timed out
$errorInfo
$errorDump java.net.SocketTimeoutException:Read timed out
$error Read timed out
$localizedError Read timed out
$errorType java.net.SocketTimeoutException
$user
$time 2011-10-25 09:39:29 EDT
$error Read timed out
$errorType java.net.SocketTimeoutException
This is the code I am using:
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class HttpXmlPost {
public static void main(String[] args)
{
String url = "https://someurlhere.com";
String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><xmlTag></xmlTag>";
String content = request(xmlStr, url);
System.out.println(content);
}
private static String request(String xmlStr, String url) {
boolean success = false;
String content = "";
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httpPost = new HttpPost(url.trim());
InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(xmlStr.getBytes() ), -1);
reqEntity.setContentType("application/xml");
reqEntity.setChunked(true);
httpPost.setEntity(reqEntity);
System.out.println("Executing request " + httpPost.getRequestLine());
HttpResponse response = httpclient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if(response.getStatusLine().getStatusCode() == 200){
success = true;
}
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
System.out.println("Chunked?: " + resEntity.isChunked());
}
BufferedReader reader = new BufferedReader(new InputStreamReader(resEntity.getContent()));
StringBuilder buf = new StringBuilder();
char[] cbuf = new char[ 2048 ];
int num;
while ( -1 != (num=reader.read( cbuf ))) {
buf.append( cbuf, 0, num );
}
content = buf.toString();
EntityUtils.consume(resEntity);
}
catch (Exception e) {
System.out.println(e);
}
finally {
httpclient.getConnectionManager().shutdown();
}
return content;
}
}
Whatever XML I pass in doesn't seem to matter, it gives the same error no matter what. Note that this actually works with some URLs. For example, if I put https://www.facebook.com, it goes through. However, it doesn't work for my specified URL. I thought it might be a certificate issue, tried to add some code to trust any certificate, didn't seem to work either, though I may have done it wrong. Any help is appreciated.
Based on the SocketTimeoutException in the first line of the response HTML, I'm guessing that the component which implements the handler for the URL to which you are posting is having some connection problems to a source system it needs to generate the response data.
Basically, it looks like the problem is on the server, not your client.

Categories