1

I have this code which is able to upload a JPEG file to the server but the file is not recognized as JPEG. I think my problem is about encoding the JPEG file correctly. My solution is essentially the same as this one. I have tried other variants in appending the JPEG bytes using FileInputStream and using DataOutputStream instead of OutputStreamWriter, etc to no avail. Any suggestion appreciated.

final String boundary = "==================";
final String mimeType = "image/jpeg";
final int IMAGE_QUALITY = 100;

URL url = null;
HttpURLConnection urlConnection = null;
OutputStreamWriter request = null;
String response = null;

try {
    url = new URL(params[0]);
    urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);     ///
    urlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    urlConnection.setRequestMethod("POST");

    OutputStream outputStream= urlConnection.getOutputStream();

    request = new OutputStreamWriter(outputStream);
    request.append("--" + boundary).append("\n");
    request.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + imageFileName + "\"").append("\n\n");
    request.append("Content-Type: " + mimeType).append("\n\n");
    request.append("Content-Encoding: base64").append("\n\n");

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    imageThumbnail.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY, stream);
    byte[] byteArray = stream.toByteArray();
    //request.append(new String(byteArray)).append("\n");
    String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
    request.append(encodedImage);

    request.append("--" + boundary + "--");
    request.flush();
    request.close();

    String line = null;
    InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
    BufferedReader reader = new BufferedReader(isr);
    StringBuilder sb = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        sb.append(line).append("\n");
    }
    response = sb.toString();   // = "Success"

    isr.close();
    reader.close();

} catch (MalformedURLException e) {
    e.printStackTrace();
    response = "Malformed URL";

} catch (IOException e) {
    e.printStackTrace();
    response = "IO Exception";
}

return response;  
Community
  • 1
  • 1
rockhammer
  • 957
  • 2
  • 13
  • 38
  • `I think my problem is about encoding the JPEG file correctly.`. What kind of encoding? And why would you encode it? Better upload the file 'as is'. – greenapps Feb 16 '17 at 17:34
  • `OutputStreamWriter request = null;`. Why are you calling an output stream writer a 'request'? You write unreadble code in this way. – greenapps Feb 16 '17 at 17:39
  • `.append("\n\n");`. You have too much of those empty lines. – greenapps Feb 16 '17 at 17:43

1 Answers1

0

Thanks to this post here, solution is as follows:

final String boundary = "==================";
final String twoHyphens = "--";
final String crlf = "\r\n";
final String mimeType = "image/jpeg";
final int IMAGE_QUALITY = 100;

URL url = null;
HttpURLConnection urlConnection = null;
DataOutputStream dos;
String response = null;

try {
    url = new URL(params[0]);
    urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);     ///
    urlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    //urlConnection.setRequestProperty("Content-Type", "image/jpeg");
    urlConnection.setRequestMethod("POST");

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    imageThumbnail.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY, stream);
    byte[] byteArray = stream.toByteArray();

    dos = new DataOutputStream(urlConnection.getOutputStream());
    dos.writeBytes(twoHyphens + boundary + crlf);
    dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + imageFileName + "\"" + crlf);
    dos.writeBytes("Content-Type: " + mimeType + crlf);
    dos.writeBytes(crlf);
    dos.write(byteArray);
    dos.writeBytes(crlf);
    dos.writeBytes(twoHyphens + boundary + twoHyphens);
    dos.flush();
    dos.close();

    String line = null;
    InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
    BufferedReader reader = new BufferedReader(isr);
    StringBuilder sb = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        sb.append(line).append("\n");
    }
    response = sb.toString();

    isr.close();
    reader.close();

} catch (MalformedURLException e) {
    e.printStackTrace();
    response = "Malformed URL";

} catch (IOException e) {
    e.printStackTrace();
    response = "IO Exception";
}

return response;

I have these inside the @Override protected String doInBackground(String... params) of an AsyncTask<String, Void, String>

Community
  • 1
  • 1
rockhammer
  • 957
  • 2
  • 13
  • 38