Server side expect image to be send in byte array, I am able upload image successfully(200 response) but when check image in server image get corrupted(image can't be open).
I tried following ways upload image(in byte array).
1st way
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.addHeader("Content-Type", "multipart/form-data");
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
@Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File("filepath");
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
2nd way
HttpPost httppost = new HttpPost(url);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,
new AndroidMultiPartEntity.ProgressListener() {
@Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File("filepath");
FileInputStream fis = new FileInputStream(sourceFile);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum); //no doubt here is 0
//Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
System.out.println("read " + readNum + " bytes,");
}
} catch (IOException ex) {
}
httppost.addHeader("Content-Type", "multipart/form-data");
httppost.setEntity(new ByteArrayEntity(buf));
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
In both cases image getting upload but its get corrupted (not viewable) after upload.
Could someone please me know what I am doing wrong? How can I upload image in byte array to server without getting image corrupted?
Here's a sample upload image function that I have used and this is working. However, I have implemented the image uploading with
Volley. You might require some changes in the function to make it work in your case.To use
Volley, you need to add the following dependency in yourbuild.gradlefile.