How to upload image using MultipartEntity in Android HttpPost? - android

Image not upload using MultipartEntity.
Gives status code 200 but image not updated on serverside.
String responseBody;
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(
"http__zz/upload_picture?key=abc&property_id=10");
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM).toString()
+ "/Camera/Test.jpg");
ContentBody encFile = new FileBody(file, "image/png");
entity.addPart("picture", encFile);
request.setEntity(entity);
ResponseHandler<String> responsehandler = new BasicResponseHandler();
responseBody = client.execute(request, responsehandler);
if (responseBody != null && responseBody.length() > 0) {
Log.w("TAG", "Response image upload" + responseBody);
}

Try using a ByteArrayBody instead of a FileBody:
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM).toString()
+ "/Camera/Test.jpg");
Bitmap b = BitmapFactory.decodeFile(file;
ByteArrayOutputStream bao = new ByteArrayOutputStream();
b.compress(CompressFormat.JPEG, 100, bao);
ByteArrayBody body = new ByteArrayBody(bao.toByteArray(), "image/jpeg", "picture");
entity.addPart("picture", body);

Why don't you try to send it as base64 encoded string?

the best way to do this is to implement an IntentService and notify status with broadcast intents. please check out this code from git its work for me
https://github.com/alexbbb/android-upload-service

Related

Sending Multipart/Form request with multiple parameters?

I am trying to upload a picture to a server and i am getting different responses from the server depending upon the entity that i am sending.
When i send
FileBody fb = new FileBody(new File(filePath), "image/jpeg");
StringBody contentString = new StringBody(directoryID + "");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("file", fb);
entity.addPart("directory_id", contentString);
postRequest.setEntity(entity);
HttpResponse response = httpClient.execute(postRequest);
// Read the response
String jsonString = EntityUtils.toString(response.getEntity());
The response i get is {"status":"Success","code":"200","message":"File has been uploaded Successfully"}
if i send the same file in this way
Bitmap bitmapOrg = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] data = bao.toByteArray();
StringBody contentString = new StringBody(directoryID + "");
ByteArrayBody ba = new ByteArrayBody(data, "image/jpeg", "file");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("file", ba);
entity.addPart("directory_id", contentString);
postRequest.setEntity(entity);
HttpResponse response = httpClient.execute(postRequest);
// Read the response
String jsonString = EntityUtils.toString(response.getEntity());
The response that i get now is {"status":"Failure","code":"501","message":"Invalid File to upload"}
So i was wondering Why is there difference between the two responses
?
Am i sending the post request parameter the right way ?
What do i have to do to post video in the same way ?
Below is the complete code for reference
public void uploadFile(int directoryID, String filePath) {
Bitmap bitmapOrg = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
String upload_url = BASE_URL + UPLOAD_FILE;
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] data = bao.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(upload_url);
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
try {
// Set Data and Content-type header for the image
FileBody fb = new FileBody(new File(filePath), "image/jpeg");
ByteArrayBody ba = new ByteArrayBody(data, "image/jpeg", "file");
StringBody contentString = new StringBody(directoryID + "");
// If i do this
entity.addPart("file", fb);
// I get a valid response
// If i do this
entity.addPart("file", ba);
// I get an invalid response
entity.addPart("directory_id", contentString);
postRequest.setEntity(entity);
HttpResponse response = httpClient.execute(postRequest);
// Read the response
String jsonString = EntityUtils.toString(response.getEntity());
Log.e("response after uploading file ", jsonString);
} catch (Exception e) {
Log.e("Error in uploadFile", e.getMessage());
}
}
I was able to solve this problem so i am posting this answer because it might help others facing the same issue.
The problem was that the server to which i was uploading the picture file only parsed files having extensions JPEG, PNG, GIF etc and it ignored the rest of the files.
The image file that i was sending in the form of ByteArrayBody had the filename attribute without extension which as a result lead to this problem.
ByteArrayBody ba = new ByteArrayBody(data, "image/jpeg", "file");
entity.addPart("file", ba);
I replaced it with
ByteArrayBody ba = new ByteArrayBody(data, "image/jpeg", "file.jpeg");
entity.addPart("file", ba);
and it worked.

Sending images and videos to server in android

I am creating an android application for taking photos and videos. After capture images I want to send this image with date and some text to web server. In server side I am making an application with this pictures and videos. The image captured will be saved in memory card. How can I send image with text using JSON. Also I want to send Videos to the web server.
You can do this with a Multipart post request:(This way, you dont need to create json)
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(serverURL);
MultipartEntity postEntity = new MultipartEntity();
File file = new File("Your File path on SD card");
postEntity.addPart("fileupload", new FileBody(file, "image/jpeg"));
postEntity.addPart("loginKey", new StringBody(""+loginKey));
postEntity.addPart("message", new StringBody(message));
postEntity.addPart("token", new StringBody(token));
post.setEntity(postEntity);
response = client.execute(post);
You have to add this mime4j library.
try this to uplaod text ,image to server in asynctask
FileBody filebodyVideo = new FileBody(new File(
"Sd Card VideoPath"));
FileBody filebodyVideo1 = new FileBody(new File("Video Upload url"));
StringBody Title= new StringBody("Put Title Here");
StringBody description= new StringBody("Put Desc Here");
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("image", filebodyVideo);
multipartContent.addPart("Title", Title);
multipartContent.addPart("Description", description);
httppost.setEntity(multipartContent);
You can use this code in your asynctask:
File file = new File("Your File path on SD card");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost("YourUrl");
MultipartEntity entity = new MultipartEntity();
entity.addPart("YourKey",new StringBody("Your Text"));
entity.addPart("File", new FileBody(file));
httpost.setEntity(entity);
HttpResponse response = httpclient.execute(httpost);

Error when uploading image to android

I'm trying to upload an image from android to server use JSON+Base64.That's work when I used an emulator.But when I used my phone, my image is lost..please help
I can not post image, please see image here:http://i.upanh.com/rtnezb and
http://i.upanh.com/rtneqi
And this's my code:
photo = BitmapFactory.decodeResource(getResources(), R.drawable.nocamera);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, baos);
imageInByte = baos.toByteArray();
ImageBase64=Base64.encodeBytes(imageupdate);
Thanks so much!
Try using a Mutipart entity to upload the image file. Yo must download "httpmime-4.2.3.jar" library, here is a sample code from one of my projects that works perfect. I hope that can help you.
DefaultHttpClient httpClient = new DefaultHttpClient();
InputStream is = null;
String json = "";
JSONObject jObj;
try {
HttpPost httpPost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
File img = new File("local_image_path_here");
entity.addPart("param_name_here", new FileBody(img));
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
catch (Exception e) {
e.printStackTrace();
}

Foursquare Android upload photo error

I am adding a photo after checkin. I am using that checkinId to add photo. I am getting error response from post request.
{"meta":{"code":400,"errorType":"param_error","errorDetail":"Cannot add photo to this checkin (it is a duplicate)"},"response":{}}
String URL_UPLOAD_PHOTO = "https://api.foursquare.com/v2/photos/add";
entity.addPart("v", new StringBody(sdf.format(cal.getTime())));
entity.addPart("checkinId", new StringBody(checkinId));
entity.addPart("public", new StringBody("1"));
entity.addPart("oauth_token", new StringBody(FoursquareConstants.sharedPreference.getToken()));
ByteArrayBody imgBody = new ByteArrayBody(FrameActivity.tempPicByte, "image/jpeg", "happyPhoto");
entity.addPart("image", imgBody);
What's the problem?
This means the photo has already been uploaded.
The below code works for me when uploading images.
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bitmapdata = stream.toByteArray();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://api.foursquare.com/v2/photos/add");
try
{
MultipartEntity entity = new MultipartEntity();
entity.addPart("v", new StringBody("20121210"));
entity.addPart("venueId", new StringBody(venue.getId()));
entity.addPart("public", new StringBody("1"));
entity.addPart("oauth_token", new StringBody(mAccessToken));
ByteArrayBody imgBody = new ByteArrayBody(bitmapdata, "image/jpeg", "FS_image");
entity.addPart("image",imgBody);
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
Log.v("response","" +response);
responseResult = inputStreamToString(response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e)
{
Log.d(TAG, "Opening URL " +e);
}

uploading image on web: getting html source code as response

I am trying to upload image on web server, but whenever it tries it is sending me html source code as response and image is not uploaded there. My code is:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
bitMap.compress(Bitmap.CompressFormat.JPEG, 100, byteStream);
byte[] buffer = byteStream.toByteArray();
ByteArrayBody body = new ByteArrayBody(buffer,"profile_image");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("b#gmail.com.jpg", body);
post.setEntity(entity);
System.out.println("post entity length "+entity.getContentLength());
ResponseHandler handler = new BasicResponseHandler() ;
String response = client.execute(post,handler);
Thanks in advance!!!
Look at this Example http://vikaskanani.wordpress.com/2011/01/11/android-upload-image-or-file-using-http-post-multi-part/
And change YourUrl

Categories

Resources