Search code examples
javaandroidimage-uploadingasyncfileuploadloopj

Android : To upload an image using AsyncHttp POST


I am having a camera intent activity , I am trying to POST an image selected by the user , to the server. But every time it is giving me Java SSL Socket Exception . Below is the method which i have tried to implement for uploading the image to the server .

private void postImage(String url) {
        Context context = this.getApplicationContext();
        File file = new File(getFilePath());
        MimeTypeMap map = MimeTypeMap.getSingleton();
        String ext = FilenameUtils.getExtension(file.getName());
        String mime_type = map.getMimeTypeFromExtension(ext);
        MultipartEntity form = new MultipartEntity();
        form.addPart("files[]", new FileBody(file, mime_type, "UTF-8"));
        AsyncHttpClient client = new AsyncHttpClient();
        client.post(context, url, form, mime_type, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject jsonObject1) {
                // called when response HTTP status is "200 OK"
                if (statusCode == 200) {
                    try {
                        String url = jsonObject1.getString("imageUrl");
                        String blobkey = jsonObject1.getString("blobKey");
                        Log.d(TAG, "IMAGE URL : " + url + " \n BlobKey : " + blobkey + " ");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable e, JSONObject jsonObject1) {
                Log.d(TAG, "Status Code : " + statusCode);
            }

            @Override
            public void onRetry(int retryNo) {
                // called when request is retried
            }
        });
    }

Solution

  • AsyncHttpClient supports uploading files. But you should use it like this:

    RequestParams params= new RequestParams();
    //params.put("file", new File(filePath));
    params.put("file", new File(filePath), contentType);
    AsyncHttpClient client = new AsyncHttpClient();
    //client.post(url, params, listener);
    client.put(url, params, listener);