Since the Android developers recommend to use the HttpURLConnection
class, I was wondering if anyone can provide me with a good example on how to send a bitmap
based on Mihai's solution, if anyone has the problem of saving images on the server like what happened on my server. change the Bitmap to bytebuffer part to :
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100,bos);
byte[] pixels = bos.toByteArray();
I found using okHttp a lot easier as I could not get any of these solutions to work: https://stackoverflow.com/a/37942387/447549
I have no idea why the HttpURLConnection
class does not provide any means to send files without having to compose the file wrapper manually. Here's what I ended up doing, but if someone knows a better solution, please let me know.
Input data:
Bitmap bitmap = myView.getBitmap();
Static stuff:
String attachmentName = "bitmap";
String attachmentFileName = "bitmap.bmp";
String crlf = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
Setup the request:
HttpURLConnection httpUrlConnection = null;
URL url = new URL("http://example.com/server.cgi");
httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setUseCaches(false);
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setRequestProperty("Connection", "Keep-Alive");
httpUrlConnection.setRequestProperty("Cache-Control", "no-cache");
httpUrlConnection.setRequestProperty(
"Content-Type", "multipart/form-data;boundary=" + this.boundary);
Start content wrapper:
DataOutputStream request = new DataOutputStream(
httpUrlConnection.getOutputStream());
request.writeBytes(this.twoHyphens + this.boundary + this.crlf);
request.writeBytes("Content-Disposition: form-data; name=\"" +
this.attachmentName + "\";filename=\"" +
this.attachmentFileName + "\"" + this.crlf);
request.writeBytes(this.crlf);
Convert Bitmap
to ByteBuffer
:
//I want to send only 8 bit black & white bitmaps
byte[] pixels = new byte[bitmap.getWidth() * bitmap.getHeight()];
for (int i = 0; i < bitmap.getWidth(); ++i) {
for (int j = 0; j < bitmap.getHeight(); ++j) {
//we're interested only in the MSB of the first byte,
//since the other 3 bytes are identical for B&W images
pixels[i + j] = (byte) ((bitmap.getPixel(i, j) & 0x80) >> 7);
}
}
request.write(pixels);
End content wrapper:
request.writeBytes(this.crlf);
request.writeBytes(this.twoHyphens + this.boundary +
this.twoHyphens + this.crlf);
Flush output buffer:
request.flush();
request.close();
Get response:
InputStream responseStream = new
BufferedInputStream(httpUrlConnection.getInputStream());
BufferedReader responseStreamReader =
new BufferedReader(new InputStreamReader(responseStream));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
responseStreamReader.close();
String response = stringBuilder.toString();
Close response stream:
responseStream.close();
Close the connection:
httpUrlConnection.disconnect();
PS: Of course I had to wrap the request in private class AsyncUploadBitmaps extends AsyncTask<Bitmap, Void, String>
, in order to make the Android platform happy, because it doesn't like to have network requests on the main thread.
Here is what i did for uploading photo using post request.
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");
StringBody contentString = new StringBody(directoryID + "");
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());
Log.e("response after uploading file ", jsonString);
} catch (Exception e) {
Log.e("Error in uploadFile", e.getMessage());
}
}
NOTE: This code requires libraries so Follow the instructions here in order to get the libraries.