How to upload file from Android to server via POST Android 08.10.2016

On server side we can follow advices for Meteor.js or Django.

On Android side I'm going to use Asynchronous HTTP Client.

An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries. All requests are made outside of your app’s main UI thread, but any callback logic will be executed on the same thread as the callback was created using Android’s Handler message passing. You can also use it in Service or background thread, library will automatically recognize in which context is ran.

Add a following dependency in your project build

compile 'com.loopj.android:android-async-http:1.4.9'

It is very easy to fetch raw string from the web using Asynchronous Http Client. Just call TextHttpResponseHandler() callback and receive result as responseString.

new AsyncHttpClient().get("http://server.com", new TextHttpResponseHandler() {
    @Override
    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
        Toast.makeText(MainActivity.this, responseString, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSuccess(int statusCode, Header[] headers, String responseString) {
        // responseString contain html from http://server.com
        Toast.makeText(MainActivity.this, responseString, Toast.LENGTH_SHORT).show();
    }    
});

Handling JSON is very popular for data transfer, you don’t need to worry about parsing JSON into JSONObject or into JSONArray, JsonHttpResponseHandler() does all the parsing for you, all you need to is make them use.

Getting JSONObject

AsyncHttpClient client = new AsyncHttpClient();
client.get("http://server.com/movie.json",new JsonHttpResponseHandler() {
    @Override
    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
        // json object is returned as a response
    }
});

Getting JSONArray

AsyncHttpClient client = new AsyncHttpClient();
client.get("http://server.com/movie.json",new JsonHttpResponseHandler() {
    @Override
    public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
        // json array is returned as a response
    }
});

Getting File

AsyncHttpClient client = new AsyncHttpClient();
client.get(url, new FileAsyncHttpResponseHandler(ctx) {
    @Override
    public void onSuccess(int statusCode, Header[] headers, File response) {
        if (statusCode == 200) {
            Log.d(TAG, "File " + response);
        } else {
            Log.d(TAG, "status error " + statusCode);
        }
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, Throwable e, File response) {
        Log.d(TAG, "onFailure: " + e.toString());
    }
});

Upload file to server via POST

File photo = new File(path);

RequestParams params = new RequestParams();
try {
    params.put("photo", photo);
} catch(FileNotFoundException e) {}

AsyncHttpClient client = new AsyncHttpClient();
client.post("http://server.com/upload", params, new JsonHttpResponseHandler() {
    ProgressDialog pd;
    @Override
    public void onStart() {
        String uploadingMessage = getResources().getString(R.string.uploading);
        pd = new ProgressDialog(MovieActivity.this);
        pd.setTitle(R.string.please_wait);
        pd.setMessage(uploadingMessage);
        pd.setIndeterminate(false);
        pd.show();
    }

    @Override
    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
        String status = JsonUtil.getJsonItem(response, "status");
        String photoID = JsonUtil.getJsonItem(response, "photoID");

        Toast.makeText(MovieActivity.this, status, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onFinish() {
        pd.dismiss();
    }
});

Useful links