使用AsyncHttpClient库上传multipart / form-data

时间:2017-10-16 05:25:02

标签: android multipartform-data asynchttpclient

我尝试使用AsyncHttpClient上传图片,我的图片上传成功,但无法从我的服务器打开,他们说“这不是有效的位图文件,或者不支持其格式。”在我使用AsyncHttpClient库之前,我可以上传并在我的服务器中查看我的图片,这是我之前上传图片的方式:

public static String POSTUpload(String url, String file) {
    int status = 0;
    String result = "";

    PostMethod method = new PostMethod(url);
    try {
        HttpClient httpClient = new HttpClient();
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(300000);
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(300000);

        method.setRequestEntity(new FileRequestEntity(new File(file), "multipart/form-data"));

        status = httpClient.executeMethod(method);
        result = String.valueOf(status);
        System.out.println("HTTP status " + method.getStatusCode() + " creating con\n\n");
    } catch (ConnectTimeoutException e) {
        Log.e("Timeout Exception: ", e.toString());
    } catch (SocketTimeoutException ste) {
        Log.e("Timeout Exception: ", ste.toString());
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        method.releaseConnection();
    }
    return result;
}

这就是我使用AsyncHttpClient上传图片的方式:

 private void POSTUpload(String url_upload, String file) {
    RequestParams params = new RequestParams();
    try {
        params.put("uploaded_file", new File(file));
        params.setForceMultipartEntityContentType(true);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    AsyncHttpClient client = new AsyncHttpClient();
    client.setMaxConnections(100);
    client.post(url_upload, params, new AsyncHttpResponseHandler() {

        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            System.out.println("statusCode " + statusCode);
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
        }
    });
}

我不明白为什么我使用这个库时我的图像无法显示。我希望有人能帮助我解决我的问题。非常感谢你。

1 个答案:

答案 0 :(得分:0)