A good approach to do multipart file upload in Android

Allan Jiang picture Allan Jiang · Dec 13, 2013 · Viewed 19.8k times · Source

I am working on a piece of code to do multipart form data POST request, which in my case is just to upload an image to server with parameters. Here's what I have now:

I have a button to trigger the multipart request, in the button OnClickListener, I have this code to spin a new thread:

new Thread(new Runnable(){

@Override
public void run() {

    String photoUri = getPhotoUri();
    String url = getEndPointUrl();

    try {   

    NewPostRequest.postFile(url, photoUri, <Other Params...>);

    } catch (Exception e) {
        // Exception Handling           
    } 
}).start();

And the NewPostRequest.postFile is just using Apache Http Client to make a request, basically like below:

HttpClient client = new DefaultHttpClient();

HttpPost post = new HttpPost(url);

MultipartEntityBuilder builder = MultipartEntityBuilder.create();    

builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

File file = new File(fileUri);

FileBody fb = new FileBody(file);

builder.addPart("file", fb);

builder.addTextBody("param", otherParam);

HttpEntity entity = builder.build();

post.setEntity(entity);

HttpResponse response = client.execute(post);      

I need to spin a new thread everytime because the recent Android releases doesn't let program to make http requests on UI thread. However, I really against to spin a random thread and let it out of control like the code above. I have tried to use Google Volley library, but it is not a handful tool when uploading large data files like image.

I was wondering what I should do to make this call more manageable?

===== UPDATE =====

I switched to use AsyncTask and it works OK for now. I will keep this question open to see if any one has better approach.

Answer

Anup Cowkur picture Anup Cowkur · Dec 13, 2013

HTTP has always been a pain point in Android. Fortunately, we have many great libraries that take care of all the hard parts.

Try out Ion.

It allows you to easily do Multi-Part requests in a background thread and let's you get callbacks on the main thread when the request is complete.

It also does other cool stuff like intelligent caching, automatic request cancellation when the calling Context goes out of scope etc.

P.S: Retrofit is another great library but I prefer Ion myself. Just a matter of preference.