使用Retrofit 2

时间:2016-05-10 02:17:43

标签: android file-upload retrofit retrofit2

我试着这几天,我真的做了一切...... 以下是邮递员的请求: enter image description here

enter image description here

我确信,所有GET参数都正确写入。我想,我上传文件的方式存在问题。

            Map<String, RequestBody> map = new HashMap<>();
            File file = new File("/storage/emulated/0/ConstructSecure/d1940b05-76d1-4d98-b4b4-b04b8247c8cb.png");
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
            String fileName = file.getName();
            map.put("attachment\"; filename=\"" + fileName + "\"", requestBody);

            //GET parameters
            Map<String, String> params = new HashMap<String, String>();
            params.put("inspectionUUID", inspectionUUID);
            params.put("noteUUID", noteUUID);
            params.put("attachmentUUID", attachmentUUID);
            params.put("noteType", noteType);
            params.put("modifiedTime", modifiedTime);

            Call<ResponseBody> call = service.upload(access_token,params,map);
            call.enqueue()....

接口:

@Multipart
    @POST("api/MediaFiles/AddMediaFile")
    Call<ResponseBody> upload(
            @Header("Authorization") String authorization,
            /* GET params */ @QueryMap Map<String, String> params,
            @PartMap Map<String, RequestBody> map
    );

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:5)

我花了很多时间来搜索,如何将文件作为字节流发送,因为Web中的所有答案都通过RequestBody解释上传,但它不适用于我的情况。 所以,这是解决方案:

InputStream in = new FileInputStream(file);
    byte[] buf = new byte[in.available()];
    while (in.read(buf) != -1) ;
    RequestBody requestBodyByte = RequestBody
            .create(MediaType.parse("application/octet-stream"), buf);
    String content_disposition = "attachment; filename=\"" + fileName + "\"";

    //GET parameters
    Map<String, String> params = new HashMap<String, String>();
    params.put("inspectionUUID", inspectionUUID);
    params.put("noteUUID", noteUUID);
    params.put("attachmentUUID", attachmentUUID);
    params.put("noteType", noteType);
    params.put("modifiedTime", modifiedTime);

    Call<ResponseBody> call = service.upload(access_token, content_disposition, requestBodyByte, params);

接口:

 @POST("api/MediaFiles/AddMediaFile")
    Call<ResponseBody> upload(
            @Header("Authorization") String authorization,@Header("Content-Disposition") String content_disposition, @Body RequestBody photo,
            /* GET params */ @QueryMap Map<String, String> params
    );

答案 1 :(得分:0)

上传图片请点击此处点击此链接

http://mushtaq.16mb.com/retrofit_example/uploads/

enter image description here

export default function(...args){}