2

I would like to know why I can successfully upload a file to a server using AsyncHttpClient but not when using SyncHttpClient.

The following setting yields successful result:

  1. MultipartEntityBuilder to build my multipart upload request + AsyncHttpClient to post it. Posting the request is triggered by tapping a button in the activity.

However, because I want to upload in an IntentService, I use SyncHttpClient, and the following setting does not successfully upload the file.

  1. MultipartEntityBuilder + SyncHttpClient + IntentService.

Below is how I build and send my request, which is the same in settings 1 and 2. The upload method is placed inside a helper class. And is invoked on a singleton instance, which when constructed its mContext is also set. client is a static instance variable of the helper class; client is a AsyncHttpClient in setting 1 and a SyncHttpClient in setting 2.

// MyUploadHelper.java

public void upload(File f) {
    String fileName = file.getName();

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addTextBody("api", "SYNO.FileStation.Upload");
    // some more addTextBody omitted
    builder.addBinaryBody("filename", file, ContentType.APPLICATION_OCTET_STREAM, fileName);

    HttpEntity entity = builder.build();

    client.post(mContext, getAbsoluteUrl(),
                entity, "multipart/form-data",
                new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        // This part can be reached in both settings. But in setting 2, the server returns "Unknown error of file operation".
                    }
                });
}

The method is called this way:

MyUploadHelper.getInstance(this).upload(aFile);

where this is an Activity in Setting 1 and an IntentService in Setting 2.

Finally, Happy New Year in advance!

Jonas
  • 534
  • 8
  • 16
  • I still cannot get that to work. But I have switched to Android's `HttpClient`, and it works in both settings. – Jonas Dec 31 '14 at 10:56
  • Hey, actually you can using Synchttpclient, just use RequestParams and put the absolute path of your image as new File into the RequestParams object. I can give you a small snippet if you want. Thanks. – Kaveesh Kanwal Aug 17 '16 at 05:53

0 Answers0