Skip to content

Instantly share code, notes, and snippets.

@rfaisal
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rfaisal/11143709 to your computer and use it in GitHub Desktop.
Save rfaisal/11143709 to your computer and use it in GitHub Desktop.
/***
* Handles uploading an image to a specified url
*/
class ImageUploaderTask extends AsyncTask<Void, Void, Boolean> {
private String mUrl;
public ImageUploaderTask(String url) {
mUrl = url;
}
@Override
protected Boolean doInBackground(Void... params) {
try {
//Get the image data
Cursor cursor = getContentResolver().query(mImageUri, null,null, null, null);
cursor.moveToFirst();
int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
String absoluteFilePath = cursor.getString(index);
FileInputStream fis = new FileInputStream(absoluteFilePath);
int bytesRead = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
while ((bytesRead = fis.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] bytes = bos.toByteArray();
// Post our image data (byte array) to the server
URL url = new URL(mUrl.replace("\"", ""));
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("PUT");
urlConnection.addRequestProperty("Content-Type", "image/jpeg");
urlConnection.setRequestProperty("Content-Length", ""+ bytes.length);
// Write image data to server
DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
wr.write(bytes);
wr.flush();
wr.close();
int response = urlConnection.getResponseCode();
//If we successfully uploaded, return true
if (response == 201
&& urlConnection.getResponseMessage().equals("Created")) {
return true;
}
} catch (Exception ex) {
Log.e(TAG, ex.getMessage());
}
return false;
}
@Override
protected void onPostExecute(Boolean uploaded) {
if (uploaded) {
mAlertDialog.cancel();
mStorageService.getBlobsForContainer(mContainerName);
}
}
}
String sasUrl = ""; // Get the sasUrl from https://hint.azure-mobile.net/api/user/sas
(new ImageUploaderTask(sasUrl)).execute();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment