I want to upload image using MultipartEntity , I have added all external jar files.
But when I try to use below code I get class not found error , and image is not able to upload.
Now I restart eclipse , Now I get error like
Unable to execute dex: Multiple dex files define Lorg/apache/http/entity/mime/FormBodyPart;
Conversion to Dalvik format failed: Unable to execute dex: Multiple dex files define Lorg/apache/http/entity/mime/FormBodyPart;
Below is my php file and java code.
<?php
$photo = $_FILES['photo']['name'];
if(!empty($_FILES['photo']['name']))
{
move_uploaded_file($_FILES['photo']['tmp_name'], "User_files/".$_FILES['photo']['name']);
}
?>
.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
File file = new File(Environment.getExternalStorageDirectory()+"/a.png");
//Log.d(TAG, "UPLOAD: setting up multipart entity");
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
//Log.d(TAG, "UPLOAD: file length = " + file.length());
//Log.d(TAG, "UPLOAD: file exist = " + file.exists());
mpEntity.addPart("photo", new FileBody(file, "image/png"));
//mpEntity.addPart("id", new StringBody("1"));
httppost.setEntity(mpEntity);
HttpResponse response;
try {
response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
}
if (resEntity != null) {
resEntity.consumeContent();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Related
I am trying to send a file from an android phone to a distant server. This is the code I used:
public void sendFile() {
try {
// HttpClient
HttpClient client = new DefaultHttpClient();
// post header
HttpPost post = new HttpPost("http://example.com/get_data.php");
// add your data
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
File folder = this.mContext.getFilesDir();
File file = new File(folder, "test.txt");
if (file.exists()) {
Log.d(TAG, "File exists : " + folder.listFiles()[0].toString());
}
builder.addPart("file", new FileBody(file));
builder.addBinaryBody("file", file);
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpResponse response = client.execute(post);
HttpEntity Httpentity = response.getEntity();
Log.v("result", EntityUtils.toString(Httpentity));
} catch (Exception e) {
e.printStackTrace();
}
}
This code should be correct since I found similar examples here and there. The problem occurs when I build the MultipartEntityBuilder:
HttpEntity entity = builder.build();
I get this error:
Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/util/Args;
at org.apache.http.entity.mime.content.AbstractContentBody.<init>(AbstractContentBody.java:48)
at org.apache.http.entity.mime.content.FileBody.<init>(FileBody.java:96)
at org.apache.http.entity.mime.MultipartEntityBuilder.addBinaryBody(MultipartEntityBuilder.java:141)
at org.apache.http.entity.mime.MultipartEntityBuilder.addBinaryBody(MultipartEntityBuilder.java:146)
at com.example.kevin.recordacceleration.Accelerometer.sendFile(Accelerometer.java:149)
The file I'm trying to send is in the internal memory, and I check its existence: it exists.
Here are the libraries that I added:
It is not the latest version because I read on an other topic that this version of httpmime and httpclient should work
Your app is missing commons-codec and commons-logging on which HttpCore and HttpClient depends. Httpmime depends on HttpClient.
Hello
I tried to upload files to android via HTTP server,
I have made HTML form to upload file, but how to receive that file to store in SDCard?
I am just receiving file's name, nothing else.
How to receive that file?
MultipartEntity entity = new MultipartEntity();
entity.addPart("type", new StringBody("photo"));
entity.addPart("data", new FileBody(new File(filepath));
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
Than read the response
heres the reference here
or use this sample without library multipart
here
private void uploadFile(File file) throws IOException {
Log.i(TAG, "Uploading " + file);
String videoName = file.getParentFile().getName();
AndroidHttpClient httpclient = AndroidHttpClient.newInstance(GoProLive.TAG);
try {
HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), ConnectTimeout);
HttpConnectionParams.setSoTimeout(httpclient.getParams(), DataTimeout);
HttpPost post = new HttpPost(
String.format("http://" + ServerName + "/upload/%s/%s", user.getUsername(), file.getName()));
post.setEntity(new FileEntity(file, "application/octet-stream"));
SimpleDateFormat df = (SimpleDateFormat) SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT, Locale.US);
df.applyPattern("EEE, dd MMM yyyy HH:mm:ss z");
post.setHeader("Last-Modified", df.format(new Date(file.lastModified())));
HttpResponse httpResponse = executePost(httpclient, post);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
file.delete();
} else {
throw new HttpException("Failed to upload file " + file.getAbsolutePath(), statusCode);
}
} finally {
httpclient.close();
}
}
I got an error using HttpPost for sending an MMS in Android.
In the Logcat it says:
ERROR/Here(447): ---------Error-----Target host must not be null, or set in parameters.
My sample code:
String url = "myurl";
HttpClient httpClient = new DefaultHttpClient();
try {
httpClient.getParams().setParameter(url, new Integer(90000)); // 90 second
HttpPost post = new HttpPost(url);
File SDCard = Environment.getExternalStorageDirectory();
File file = new File(SDCard, "1.png");
FileEntity entity;
entity = new FileEntity(file,"binary/octet-stream");
entity.setChunked(true);
post.setEntity(entity);
post.addHeader("Header", "UniqueName");
Log.i("MMSHTTP","----post---------------"+post);
HttpResponse response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
Log.e("Here",
"--------Error--------Response Status line code:" + response.getStatusLine());
}
else
{
// Here every thing is fine.
}
HttpEntity resEntity = response.getEntity();
if (resEntity == null) {
Log.e("Here","---------Error No Response!!-----");
}
} catch (Exception ex) {
Log.e("Here","---------Error-----"+ex.getMessage());
ex.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
}
How do I fix the error?
The url you're specifying is in your sample code is:
String url = "myurl";
In order for HttpClient to be able to determine the host name, you're going to need to supply a valid url. Something along the lines of:
String url = "http://myurl.com/index";
Note: The 'http://' is important so that the appropriate protocol can be determined.
This guy had the same problem.
I have some code to post an image to my php script that uploads to a database, when it adds to the database the file type is application/oct???? (what is this)
is there anyway of changing this to a jpg file at the android stage?
Below is my code
HttpClient client = new DefaultHttpClient();
String postURL = "http://10.0.2.2:90/mobileupload3.php";
HttpPost post = new HttpPost(postURL);
FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("image", bin);
reqEntity.addPart("name", new StringBody(enteredName));
reqEntity.addPart("gender", new StringBody(radio));
reqEntity.addPart("cat", new StringBody(radio2));
reqEntity.addPart("lat", new StringBody(lat));
reqEntity.addPart("lon", new StringBody(lon));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
Log.i("RESPONSE",EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
application/oct (I assume you mean application/octet-stream) is a MIME type for a general binary file.
Without more information on your method of upload, I believe that the other part of your question has already been answered on SO here.
I've been looking into this for the last day or two and can not seem to find a solution to my issue. I am trying to post an image to a server using httppost.
I have tried two ways of doing this and both complete the post but with no content i.e. the content length is 0.
The first is as follows:
String url = "MYURL";
HttpClient httpClient = new DefaultHttpClient();
try {
httpClient.getParams().setParameter("http.socket.timeout", new Integer(90000)); // 90 second
HttpPost post = new HttpPost(url);
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot,"/DCIM/100MSDCF/DSC00004.jpg");
FileEntity entity;
entity = new FileEntity(file,"binary/octet-stream");
entity.setChunked(true);
post.setEntity(entity);
post.addHeader("Header", "UniqueName");
HttpResponse response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
Log.e("Here","--------Error--------Response Status line code:"+response.getStatusLine());
}else {
// Here every thing is fine.
}
HttpEntity resEntity = response.getEntity();
if (resEntity == null) {
Log.e("Here","---------Error No Response!!-----");
}
} catch (Exception ex) {
Log.e("Here","---------Error-----"+ex.getMessage());
ex.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
}
and the second is:
String url = "MYURL";
//File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(Environment.getExternalStorageDirectory(),"/DCIM/100MSDCF/DSC00004.jpg");
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true);
// Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
Log.d("finishing", "The try catch function");
} catch (Exception e) {
// show error
}*/
As you can see I have hardcoded a path to a specific image, this is to be dynamic when I get it up and running.
Can anyone see what i'm doing wrong? Am I leaving out something? I know I use setChunked and setContenttype - is there a setContent option?
Any help would be grately appreciated.
Thanks,
jr83.
You can use upload your image by sending multipart messages; you might find this discussion useful.