上传图像文件对象android

时间:2018-11-12 09:07:25

标签: android http-post multipartform-data

我想通过HTTP POST,multipart / form-data将图像文件上传到服务器。

React Web Client可以将图像文件上传到服务器,但是Android Client无法。

当android客户端发送请求时,服务器说类型错误。

此代码是React-Web客户端代码的一部分。很好。

//Get Image file in my computer
setImage() {   
    window.$("input:file").click();
}

//Set this.state.file
onChange(e) {
    this.setState({ 
        file: e.target.files[0]
    });
}

const formData = new FormData();
formData.append('image', this.state.file);   //image file object
const result = await imageFileUpload(formData, "image");

export async function imageFileUpload(formData, type) {
    let result = '';

    await axios.post(`${AWS_LAMBDA_API_URL}?type=${type}`, formData,
    { headers: { 'Content-Type': 'multipart/form-data' }})
    .then((response) => {result = response});

    return result;
    //result give me images URL.
};

这是Android客户端代码。当我通过此代码发送请求时,服务器响应显示多部分类型错误。

imgURL看起来像“ /storage/emulated/0/DCIM/img/1493742568136.jpg”

public static String requestHttpPostLambda(String requrl, String imgURL) {
    String result = null;
    try {
        HttpClient client = new DefaultHttpClient();
        String postURL = requrl;
        HttpPost post = new HttpPost(postURL);
        post.setHeader("Content-Type", "multipart/form-data");

        File file = new File(imgURL);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("image", new FileBody(file));
        post.setEntity(builder.build());

        HttpResponse responsePOST = client.execute(post);
        HttpEntity resEntity = responsePOST.getEntity();
        if (resEntity != null) {
            result = EntityUtils.toString(resEntity);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

如何更改Android代码?

0 个答案:

没有答案