多部分改造2.0图片上传 [英] Multipart Retrofit 2.0 image upload

查看:356
本文介绍了多部分改造2.0图片上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过多部分POST请求,上传图片应具备的结构是这样的:

I am trying to upload image by POST multipart request which should have structure like this :

----------------------------- 219391268715340
内容处置:表格数据; NAME =照片[];文件名=DSCF0157-Laptop.JPG
内容类型:图像/ JPEG

-----------------------------219391268715340 Content-Disposition: form-data; name="photos[]"; filename="DSCF0157-Laptop.JPG" Content-Type: image/jpeg

(字节数据)

我的code:

        MediaType mediaType = MediaType.parse("image/jpeg");
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        byte[] byteArray = stream.toByteArray();

        RequestBody file=RequestBody.create(mediaType, byteArray);
        map.put("form-data; name=\"photos[]\"; filename=\""+filename+".jpg",file);

我使用的地图,因为@PartMap注释 - 我要上传多个文件。我的服务器返回的HTTP code 200 - 但没有文件被上传。 API调用已经过测试 - 如果使用我们的Web应用程序能够正常工作。任何知道我做错了。

I use map because of @PartMap annotation - I want to upload multiple files. My server returns http code 200 - but no files are uploaded. Api call has been tested - it works correctly if used by our web application. Any idea what I am doing wrong

推荐答案

如果您要上传多个文件使用改造2的请求时,你可以参考我的答案在问题之下

If you want to upload many files in a request using Retrofit 2, you can refer to my answer at the question below

<一个href=\"http://stackoverflow.com/questions/36491096/retrofit-multipart-request-required-multipartfile-parameter-file-is-not-$p$p/\">Retrofit - 多部分的请求:必需MultipartFile参数'文件'不是present

通过一些修改:

WebAPIService.java:

@Multipart
@POST("/api/fileupload")
Call<ResponseBody> postFiles(@Part List<MultipartBody.Part> fileList);

FileActivity.java:

...
List<MultipartBody.Part> fileList = new ArrayList<>();
for (int i = 0; i < 2; i++){
    fileList.add(body);

}
Call<ResponseBody> call = service.postFiles(fileList);
call.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call,
                           Response<ResponseBody> response) {
        Log.i(LOG_TAG, "success");
    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        Log.e(LOG_TAG, t.getMessage());
    }
});

当然,与上述code,实际上,相同的文件(体)将被上载的2份在请求中。其结果是,在Web服务器,你将有相同内容的2个文件,你可以自定义的fileList 与许多不同的文件:)

希望它帮助!

这篇关于多部分改造2.0图片上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆