How can I send large image/photo to the server using HTTP POST and JSON? I tried several methods but all methods wasn´t good (OutOfMemory Exceptions etc.).
"Classic" code:
Bitmap image; ByteArrayOutputStream stream = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.PNG, 100, stream); image.recycle(); image = null; byte[] byteArray = stream.toByteArray(); try { stream.close(); } catch (IOException e1) { } stream = null; String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT); HttpClient httpClient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(Globals.URL + "/storageUploadFile"); httppost.setHeader("Token", Globals.Token); String msg = ""; try { JSONObject jo = new JSONObject(); jo.put("fileName", fileName); jo.put("content", encoded); httppost.setEntity(new StringEntity(jo.toString()); HttpResponse response = httpClient.execute(httppost); HttpEntity httpentity = response.getEntity(); msg = EntityUtils.toString(httpentity); //... In this code I get exception here: httppost.setEntity(new StringEntity(jo.toString());
Image is saved on storage card. What do you recommend to upload the image? Send image chunk by chunk? I rather send it as one "item". I hope 2 MB is not so large. My API has parameter "content" and it´s the image in base64 encoding. Is it good way to transfer image as base64?