I have been trying to upload an image and data to Django server. I have included apache-mime4j.0.6.jar and httpmime4.0.1.jar libraries ( Project->build path->Add external jar files)
And here's the code to upload an image.
HttpResponse response = null;
try {
HttpPost httppost = new HttpPost("http://10.0.2.2:8000/mobile");
// HttpPost httppost = new HttpPost("some url");
MultipartEntity multipartEntity = new MultipartEntity(); //MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("name", new StringBody("nameText"));
multipartEntity.addPart("place", new StringBody("placeText"));
multipartEntity.addPart("tag", new StringBody("tagText"));
//multipartEntity.addPart("Description", new StringBody(Settings.SHARE.TEXT));
multipartEntity.addPart("Image", new FileBody(destination));
httppost.setEntity(multipartEntity);
httpclient.execute(httppost, new PhotoUploadResponseHandler());
} catch (Exception e) {
Log.e( "Error","error");
}
Error message:
Could not find class 'org.apache.http.entity.mime.MultipartEntity'
And I have tried manually creating libs folder and manually including jar files into /libs folder.
When I do that It fails to compile.
Error:
Conversion to Dalvik format failed with error 1 Unknown Android Packaging Problem
Tried creating fresh application including libraries. And I encountered the same error. I've tried everything possible. Can anyone tell me why this happens and how to fix it. Any help would be greatly appreciated!!
If you are using new android-sdk Try this.
Create folder named as libs
Paste your jar file in that folder.
And finally right click on your project > Build Path > Add External Archive.
That's it.This might help.Good Luck.
I upload an image from Android to a Django server using httpmime-4.2.1.jar. That is the only library that i have included and it works fine. Btw: libraries are supposed to be in the libs folder in Android projects.
this is the code that i am using for the upload.
private JSONObject uploadImage(String url, File img) throws Exception{
url = addAuthToken(url);
HttpPost post = new HttpPost(url);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fileBody = new FileBody(img, "images/jpeg");
reqEntity.addPart("image", fileBody);
post.setEntity(reqEntity);
JSONObject ret = baseRequest(post);
checkReturnStatus(ret, 201);
return ret;
}
private JSONObject baseRequest(HttpUriRequest request) throws Exception{
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
BufferedReader in = null;
try{
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer();
String line = null;
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
return new JSONObject(sb.toString());
}finally {
if(in != null) in.close();
}
}
I suggest you to use spring-android
It is a good rest api library for android and with spring-android, you can upload file easily like this.
HttpHeaders requestHeaders = ....
MultiValueMap<String, Object> message = new LinkedMultiValueMap<String, Object>();
message.add("qqfile", new FileSystemResource(filePath)); //attach file
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(
message, requestHeaders);
RestTemplate restTemplate = RestUtil.getRestTemplate( context);
ResponseEntity<YourResultDTO> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity,YourResultDTO.class);
It is very easy to use and use Apache http client on pre gingerbread and java.net.urlconnection on gingerbread and higher api level as google suggests.
I had the same problem and I solved it this way: in the java build path window, click the Order and Export tab Highlight the library you want to add then click the up (upload lib to be first)
Click ok and everything is fine.
Here is a link with photos (Android Eclipse NoClassDefFoundError for external .jar files)
Related
I have read lots of post to achieve the task like to upload image along with parameters using multipartentity and josn in android, but my problem is when i was trying to upload image and parameter without converting string to JSONobject then image has uploaded without an error but when i was trying to add response string to jsonobject then error occur in the logcat like ):
error: Value`<form of type java.lang.String cannot be converted to JSONObject.
Any one please help to resolve this issue? I want to send an image and JsonObject to an PHP Server with MultipartEntity. I am working on an app that allows the user upload an image by using HttpPost method. I use MultipartEntity and therefore I added the libraries apache-mime4j-0.6.1.jar, httpclient-4.3.1.jar, httpcore-4.3.1.jar and httpmime-4.2.1.jar into my app.
Here is my Code:
public JSONObject doFileUpload(String _fname, String _lname, String _email,
String _password, String _country, String _countrycode,
String _phone) {
File file1 = new File(selectedPath);
String urlString = "http://capstonehostingservices.com/fetch_new/app/index.php/fetch/register";
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
FileBody bin1 = new FileBody(file1);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("photo", bin1);
reqEntity.addPart("first_name", new StringBody(_fname));
reqEntity.addPart("last_name", new StringBody(_lname));
reqEntity.addPart("email", new StringBody(_email));
reqEntity.addPart("password", new StringBody(_password));
reqEntity.addPart("country", new StringBody(_country));
reqEntity.addPart("country_code", new StringBody(_countrycode));
reqEntity.addPart("phone", new StringBody(_phone));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
String response_str = EntityUtils.toString(resEntity);
json = new JSONObject(response_str);
} catch (Exception ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
return json;
}
In above code i was trying to convert response string to jsonobject, how to i achieve this?
I used selectedpath parameter as to get image path from gallary, I want to send an image and a JsonObject to an PHP Server with MultipartEntity. I am working on an app that allows the user upload an image by using HttpPost method. I use MultipartEntity and therefore I added the libraries apache-mime4j-0.6.1.jar, httpclient-4.3.1.jar, httpcore-4.3.1.jar and httpmime-4.2.1.jar into my app.
This may not be the best answer but it is a very good example to get started.
Use the following function to send file to server:
public static void postFile(String fileName) throws Exception {//fileName is path+filename of picture
String url_upload_image = "http://url-to-api/upload_photo.php";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url_upload_image);
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder
.create();
multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("file", new FileBody(new File(fileName)));
post.addHeader("id", id);//id is anything as you may need
post.setEntity(multipartEntity.build());
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
entity.consumeContent();
client.getConnectionManager().shutdown();
}
PHP file that is at http://url-to-api/upload_photo.php
<?php
$name = $_POST['id'];
$file_path = "images/";
$file_path = $file_path . basename( $_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $file_path)) {
echo "success";
echo $name;
} else{
echo "fail";
}
?>
And make sure that your directory or folder in server is Executable, Writable and Readable. I had this as the major problem. This is called 777 permission.. Believe me, this is as important as other things to consider.
I have an app on GAE at: http://1.myawesomecity.appspot.com/
FIXED:
HttpPost post = new HttpPost("http://1.myawesomecity.appspot.com/");
http_client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
String result = EntityUtils.toString( http_client.execute(post).getEntity(), "UTF-8");
String actualURL = result.substring(result.indexOf("http://"), result.indexOf("\" method"));
Log.w("asdf", "url " + actualURL );
post = new HttpPost(actualURL);
http_client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
String mime_type = "image/png";
File file = new File( filename ); //context.getFilesDir(),
entity.addPart( "myFile", new FileBody( file, mime_type));
post.setEntity( entity );
String res = EntityUtils.toString( http_client.execute(post).getEntity(), "UTF-8");
Log.w("asdf", res);
The above grabs the ACTUAL upload URL from the GAE server, and passes in the file as dictated by the CORRECT answer below.
Old Question:
As you can see, if you choose a file and hit submit, it will 404, but the file actually does get stored (as long as it is not too big, < 100kb). Don't type in anything in the first text field.
Now, putting aside how this particular app is barely functional, I'm trying to upload a file from Android onto this server.
The site's upload script uses blobstore, and the file field's name is "myFile".
Now in my Android app, I have:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(<my app's url>);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("myFile", <path to a file selected by user> ) );
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
This throws an exception.
How is this any different from me going to my site through a browser, choosing a file, and hitting submit? Why does going through a browser actually go through with uploading the file, when the Android code does not?
I know that my filepath is valid. Is there something I'm doing wrong? or is clicking on "submit" from a browser different from executing a httpclient from Android?
Uploading file to a blobstore on GAE is a two step process:
first you need to get a proper URL where to POST your data, usually people use something like "/bloburl" handler for that purpose
when you have blob upload URL, you use it in your request.
the file you send does not go as NameValuePair, it's supposed to go as a MultiPartEntity.
here's the code that works (you'll need apache http library for MultiPartEntry support):
DefaultHttpClient http_client = new DefaultHttpClient();
HttpGet http_get = new HttpGet(Config.BASE_URL + "bloburl");
HttpResponse response = http_client.execute(http_get);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String first_line = reader.readLine();
Log.w(TAG, "blob_url: " + first_line);
HttpPost post = new HttpPost(first_line);
http_client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
mime_type = "application/zip";
File file = new File( context.getFilesDir(), filename );
entity.addPart( "file", new FileBody( file, mime_type));
post.setEntity( entity );
String result = EntityUtils.toString( http_client.execute(post).getEntity(), "UTF-8");
Log.i(TAG, result);
I use this code that i found in some page but I only can upload images from my android application to the server and is working, but when i upload a video(.mp4) its saved as "file" like unknown.
public void upload() throws Exception {
//Url of the server
String url = "";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
MultipartEntity mpEntity = new MultipartEntity();
//Path of the file to be uploaded
String filepath = "";
File file = new File(filepath);
ContentBody cbFile = new FileBody(file);
//Add the data to the multipart entity
mpEntity.addPart("image", cbFile);
mpEntity.addPart("name", new StringBody("Test", Charset.forName("UTF-8")));
mpEntity.addPart("data", new StringBody("This is test report", Charset.forName("UTF-8")));
post.setEntity(mpEntity);
//Execute the post request
HttpResponse response1 = client.execute(post);
//Get the response from the server
HttpEntity resEntity = response1.getEntity();
String Response=EntityUtils.toString(resEntity);
Log.d("Response:", Response);
//Generate the array from the response
JSONArray jsonarray = new JSONArray("["+Response+"]");
JSONObject jsonobject = jsonarray.getJSONObject(0);
//Get the result variables from response
String result = (jsonobject.getString("result"));
String msg = (jsonobject.getString("msg"));
//Close the connection
client.getConnectionManager().shutdown();
}
There is any way to make this work to upload videos too?
There is not issue with this code works fine for upload videos and images, the problem was i´m missing the file extension in the name, so when the video was uploaded it should be NAME.EXTENSION not only NAME.
NOTE:
For all the people who is trying to upload a large(2MB-10GB) image or video to the server the only solution i found was encode the file in chunks and upload each chunk to the server, from there you only have to encode the chunks again. NO SIZE LIMITATION :)!!!!
I need to upload an image to my server under a specific name, but ideally, I would like to still keep image stored on the device under the original file name. This is what I tried:
myImageFile.renameTo(new File("mobileimage.jpg"));
but when the file was uploaded to the server, it did not appear to have my new name. Here is the full code that uploads the image to the server:
DefaultHttpClient mHttpClient;
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
mHttpClient = new DefaultHttpClient(params);
try {
myImageFile.renameTo(new File("mobileimage.jpg"));
HttpPost httppost = new HttpPost("http://mywebsite/mobile/image");
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("userID", new StringBody(Constants.userID));
multipartEntity.addPart("uniqueMobileID", new StringBody(Constants.uniqueMobileID));
multipartEntity.addPart("userfile", new FileBody(myImageFile));
httppost.setEntity(multipartEntity);
HttpResponse response = mHttpClient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
Log.d(TAG, "response: " + responseBody);
return responseBody;
} catch (Exception e) {
Log.d(TAG, e.getMessage());
}
How can I change the file name?
Use the constructor of FileBody that takes the fileName as an argument
Try using the other implementation of addPart when attaching the file, so that you may add the filename field to the HTTP request. Something like this:
FormBodyPart userFile = new FormBodyPart("userfile", new FileBody(myImageFile));
userFile.addField("filename","NEWNAMEOFILE.jpg");
multipartEntity.addPart(userFile);
Is it possible renameTo() is returning false? You should check your return values, especially with renameTo().
As part of my Android app, I'd like to upload bitmaps to be remotely stored. I have simple HTTP GET and POST communication working perfectly, but documentation on how to do a multipart POST seems to be as rare as unicorns.
Furthermore, I'd like to transmit the image directly from memory, instead of working with a file. In the example code below, I'm getting a byte array from a file to be used later on with HttpClient and MultipartEntity.
File input = new File("climb.jpg");
byte[] data = new byte[(int)input.length()];
FileInputStream fis = new FileInputStream(input);
fis.read(data);
ByteArrayPartSource baps = new ByteArrayPartSource(input.getName(), data);
This all seems fairly clear to me, except that I can't for the life of me find out where to get this ByteArrayPartSource. I have linked to the httpclient and httpmime JAR files, but no dice. I hear that the package structure changed drastically between HttpClient 3.x and 4.x.
Is anyone using this ByteArrayPartSource in Android, and how did they import it?
After digging around in the documentation and scouring the Internet, I came up with something that fit my needs. To make a multipart request such as a form POST, the following code did the trick for me:
File input = new File("climb.jpg");
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://localhost:3000/routes");
MultipartEntity multi = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
String line;
multi.addPart("name", new StringBody("test"));
multi.addPart("grade", new StringBody("test"));
multi.addPart("quality", new StringBody("test"));
multi.addPart("latitude", new StringBody("40.74"));
multi.addPart("longitude", new StringBody("40.74"));
multi.addPart("photo", new FileBody(input));
post.setEntity(multi);
HttpResponse resp = client.execute(post);
The HTTPMultipartMode.BROWSER_COMPATIBLE bit is very important. Thanks to Radomir's blog on this one.
try this:
HttpClient httpClient = new DefaultHttpClient() ;
HttpPost httpPost = new HttpPost("http://example.com");
MultipartEntity entity = new MultipartEntity();
entity.addPart("file", new FileBody(file));
httpPost.setEntity(entity );
HttpResponse response = null;
try {
response = httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
Log.e("ClientProtocolException : "+e, e.getMessage());
} catch (IOException e) {
Log.e("IOException : "+e, e.getMessage());
}
Perhaps you can do following step to import library into your Android.
requirement library
- apache-mime4j-0.6.jar
- httpmime-4.0.1.jar
Right click your project and click properties
select java build path
select tab called "Order and Export"
Apply it
Fully uninstall you apk file with the adb uninstall due to existing apk not cater for new library
install again your apk
run it
Thanks,
Jenz
I'm having the same problem. I'm trying to upload an image through MultiPart Entity and it seens that the several updates on HttpClient/MIME are cracking everything. I'm trying the following code, falling with an Error "NoClassDefFoundError":
public static void executeMultipartPost(File image, ArrayList<Cookie> cookies, String myUrlToPost) {
try {
// my post instance
HttpPost httppost = new HttpPost(myUrlToPost);
// setting cookies for the connection session
if (cookies != null && cookies.size() > 0) {
String cookieString = "";
for (int i=0; i<cookies.size(); ++i) {
cookieString += cookies.get(i).getName()+"="+cookies.get(i).getValue()+";";
}
cookieString += "domain=" + BaseUrl + "; " + "path=/";
httppost.addHeader("Cookie", cookieString);
}
// creating the http client
HttpClient httpclient = new DefaultHttpClient();
// creating the multientity part [ERROR OCCURS IN THIS BELLOW LINE]
MultipartEntity multipartEntity = new MultipartEntity();
multipartEntity.addPart("photoupload", new FileBody(image));
httppost.setEntity(multipartEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
} catch (Exception e) {}
}
This method is fully compilable and uses the httpclient-4.0.1.jar and httpmime-4.2.jar libs, but again, I remember that it crashs in the commented line for me.