Image upload from android app - android

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();

Related

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

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.

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

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

Dynamically conversion of image to binary and vice versa

How can I convert image to binary data..???
I want to send that converted binary data to
another device or to the web server.
Which mechanism is best to do this.?
Image is in Bitmap then use the following code to convert that image to binary. By using following code
Bitmap photo;// this is your image.
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
To get Image From Binary use the following sample:
Bitmap bMap = null;
bMap = BitmapFactory.decodeByteArray(byteArray,0,byteArray.length);
I found a good example for uploading the image to the server.
create a bitmap variable before do anything.
variable to set a name to the image into SD card.
this variable, you have to put the path for the File, It's up to you.
sendData is the function name, to call it, you can use something like
sendData(null).
remember to wrap it into a try catch.
private Bitmap bitmap;
public static String exsistingFileName = "";
public void sendData(String[] args) throws Exception {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
// here, change it to your php;
HttpPost httpPost = new HttpPost("http://www.myURL.com/myPHP.php");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
bitmap = BitmapFactory.decodeFile(exsistingFileName);
// you can change the format of you image compressed for what do you want;
// now it is set up to 640 x 480;
Bitmap bmpCompressed = Bitmap.createScaledBitmap(bitmap, 640, 480, true);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// CompressFormat set up to JPG, you can change to PNG or whatever you want;
bmpCompressed.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
// sending a String param;
entity.addPart("myParam", new StringBody("my value"));
// sending a Image;
// note here, that you can send more than one image, just add another param, same rule to the String;
entity.addPart("myImage", new ByteArrayBody(data, "temp.jpg"));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
BufferedReader reader = new BufferedReader(new InputStreamReader( response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
} catch (Exception e) {
Log.v("myApp", "Some error came up");
}
}
Try this
Let img contains Bitmap image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "png", baos);
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
imageInByte now contains bytedata of bitmap image.
For converting reverse
Bitmap bp = BitmapFactory.decodeByteArray(imgArray, 0,imgArray.length);
Hope this may help you
if you want to send to webserver use HttpPost request using HttpClient

Categories

Resources