private class UploadFile extends AsyncTask<Void, Integer, String> {@Overrideprotected void onPreExecute() {// set a status bar or show a dialog to the user heresuper.onPreExecute();}
@Overrideprotected void onProgressUpdate(Integer... progress) {// progress[0] is the current status (e.g. 10%)// here you can update the user interface with the current status}
@Overrideprotected String doInBackground(Void... params) {return uploadFile();}
private String uploadFile() {
String responseString = null;HttpClient httpClient = new DefaultHttpClient();HttpPost httpPost = new HttpPost("http://example.com/upload-file");
try {AndroidMultiPartEntity ampEntity = new AndroidMultiPartEntity(new ProgressListener() {@Overridepublic void transferred(long num) {// this trigger the progressUpdate eventpublishProgress((int) ((num / (float) totalSize) * 100));}});
File myFile = new File("/my/image/path/example.jpg");
ampEntity.addPart("fileFieldName", new FileBody(myFile));
totalSize = ampEntity.getContentLength();httpPost.setEntity(ampEntity);
// Making server callHttpResponse httpResponse = httpClient.execute(httpPost);HttpEntity httpEntity = httpResponse.getEntity();
int statusCode = httpResponse.getStatusLine().getStatusCode();if (statusCode == 200) {responseString = EntityUtils.toString(httpEntity);} else {responseString = "Error, http status: "+ statusCode;}
} catch (Exception e) {responseString = e.getMessage();}return responseString;}
@Overrideprotected void onPostExecute(String result) {// if you want update the user interface with upload resultsuper.onPostExecute(result);}
}