Uploading image to server with Android HttpClient.execute(postRequest) - android

Here is the code...
Bitmap bm = myImageToUpload;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(myServerURL);
ByteArrayBody bab = new ByteArrayBody(data, imageName);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("uploadedfile", bab);
reqEntity.addPart("fileName", new StringBody("image"));
reqEntity.addPart("mimeType", new StringBody("images/jpeg"));
reqEntity.addPart("extraInfo", new StringBody(extraInfo));
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
This code uploads my image along with some other information to the server. Is there a better way to do this?
My concerns - It is slow, Sometimes takes 20 minuets to upload a large image to the server. The size of the image on the server is larger than the original.
at the very least, how can I upload the image so that the image on the server is the exact same size as the image on my android device?

reqEntity.addPart("uploadedfile", new FileBody(new File(myImageToUpload)));
This might be faster, and reads more easily, unless you really need the byte array.

Related

No Class Def Found Error org.apache.ContentType (Android Studio)

Good Day.I done heaps of researches and used every answer i found but nothing helped!Im trying to upload simple image to php server in bytes with this code
#Override
protected String doInBackground(Void... params) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bos);
byte[] data = bos.toByteArray();
String fileName = String.format("File_%d.png", new Date().getTime());
ByteArrayBody bab = new ByteArrayBody(data, fileName);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://192.168.1.100/paqqy/user/registration/platform/android");
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("file", bab);
Whats funny is that the damned android studio keeps giving me NoClassDefFound Error at line of ByteArrayBody bab = new ByteArrayBody(data, fileName); but i did try everything...Rebuilding,Cleaning,Gradle Sync,download all versions of HttpMime,HttpCore,HttpCore-cache and so on...but still this freaking android studio will give it to me.In eclipse it was easy,was using order and export in that case and error had gun,but here i just dont know what to do,please help me a little im so angry and desperate!

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.

How to upload image using MultipartEntity in Android HttpPost?

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

Image upload from android app

In my application I'm uploading an image on to the server. Here in the below code I'm uploading an image from the drawable folder.
But how can I upload an image from an imageview from the layout xml?
similarly like findviewbyid.imgid
My layout name is main.xml and image id is imgid
kindly help me...
Bitmap bitmap =
BitmapFactory.decodeResource(getResources(),R.drawable.avatar);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",image_str));
We can upload image using Base64 string and multipart entity
for base64 string
ByteArrayOutputStream baos = new ByteArrayOutputStream();
btMap.compress(Bitmap.CompressFormat.JPEG, 100, baos); // bm is the
byte[] b = baos.toByteArray();
base64String = Base64.encodeBytes(b);
and for multipart
HttpPost httppost = new HttpPost("http://localhost:8080/upload.php");
File file = new File(yourimagepath);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();

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