Skip to content

Instantly share code, notes, and snippets.

@fiftin
Last active September 13, 2015 18:21
Show Gist options
  • Save fiftin/23d5c02b18d3ec63a6c1 to your computer and use it in GitHub Desktop.
Save fiftin/23d5c02b18d3ec63a6c1 to your computer and use it in GitHub Desktop.
Async uploading an image as file to the server from Android application
private class HttpUploadImageTask extends AsyncTask<String, Void, Boolean> {
final Bitmap imageBitmap;
public HttpUploadImageTask(final Bitmap imageBitmap) {
this.imageBitmap = imageBitmap;
}
@Override
protected Boolean doInBackground(String... urls) {
for (final String u : urls) {
try {
process(new URL(u));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
private void process(final URL url) throws IOException {
final String lineEnd = "\r\n";
final String twoHyphens = "--";
final String boundary = "*****";
final String filename = "unnamed";
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("uploaded_file", filename);
final DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(twoHyphens + boundary + lineEnd);
out.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ filename + "\"" + lineEnd);
out.writeBytes(lineEnd);
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
out.writeBytes(lineEnd);
out.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
final int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.i("uploadImage", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
out.flush();
out.close();
}
@Override
protected void onPostExecute(Boolean result) {
Log.i("uploadImage", "OK");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment