Retrofit2 使用@Multipart上传文件

1、上传单个文件

1.1定义接口

 
    @Multipart
    @POST("uploadImgs")
    Call>> uploadSingleImg(@Part("description") RequestBody description, @Part MultipartBody.Part file);

1.2接口传参

    public void uploadImg(Object pcObj, String fileUrl) {

        File file = new File(fileUrl);
        // 创建 RequestBody,用于封装构建RequestBody
        // RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
         RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpg"), file);

        // MultipartBody.Part  和后端约定好Key,这里的partName是用file
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);

        // 添加描述
        String descriptionString = "hello, 这是文件描述";
        RequestBody description = RequestBody.create(MediaType.parse("multipart/form-data"), descriptionString);

        // 执行请求
        serviceApi.uploadSingleImg(description, body).enqueue(new BaseViewModel.HttpRequestCallback>() {

            @Override
            public void onSuccess(List result) {
                super.onSuccess(result);
            }

            @Override
            public void onFailure(int status, String message) {
                super.onFailure(status, message);
            }
        });

    }

2、上传多个文件

2.1定义接口

   @Multipart
    @POST("uploadImgs")
    Call>> uploadMultiImgs(@PartMap Map maps);

2.2接口传参

   public void uploadImgs(Object pcObj, List imgStrs) {
        Map map = new HashMap<>();
        for (String imgUrl : imgStrs) {
            File file = new File(imgUrl);
            // create RequestBody instance from file
            // RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpg"), file);
            //注意:file就是与服务器对应的key,后面filename是服务器得到的文件名
            map.put("file\"; filename=\"" + file.getName(), requestFile);
        }

        // 执行请求
        serviceApi.uploadMultiImgs(map).enqueue(new BaseViewModel.HttpRequestCallback>() {

            @Override
            public void onSuccess(List result) {
                super.onSuccess(result);
            }

            @Override
            public void onFailure(int status, String message) {
                super.onFailure(status, message);
            }
        });
    }

3、上传图文(图文混传)

3.1定义接口

    @Multipart
    @POST("gather/vehicle")
    Call> uploadInfo(@Header("jwt-token") String token, @PartMap Map files);

3.2接口传参

 private void uploadInfo(VehicleResponse response) {
        String token = SpUtil.getJwtToken(mContext);
        Map map = new HashMap<>();
        File file = new File(response.getImgUrl());
        // map.put(String.format("file\"; filename=\"" + file.getName()), RequestBody.create(MediaType.parse("multipart/form-data"), file));
        //map.put(String.format("imageFile\"; filename=\"123456.jpg"), RequestBody.create(MediaType.parse("image/jpg"), file));//图片名称不能包含中文字符
        map.put(String.format("file\"; filename=\"" + file.getName()), RequestBody.create(MediaType.parse("image/jpg"), file));
        map.put("plateNo", toRequestBody(response.getPlateNo()));
        map.put("plateColor", toRequestBody(response.getPlateColor()));
        map.put("deviceId", toRequestBody(BizUtil.getImeiString(mContext)));
        map.put("longitude", toRequestBody(String.valueOf(response.getLongitude())));
        map.put("latitude", toRequestBody(String.valueOf(response.getLatitude())));
        map.put("address", toRequestBody(response.getAddress() + "_非空值"));
        map.put("gatherTime", toRequestBody(DateUtil.Long2String(response.getGatherTime(), "yyyy-MM-dd HH:mm:ss")));

        serviceApi.uploadInfo(token, map).enqueue(new HttpRequestCallback() {
            @Override
            public void onSuccess(VehicleResponse result) {
                super.onSuccess(result);
            }
            @Override
            public void onFailure(int status, String message) {
                super.onFailure(status, message);
            }
        });
    }

    private RequestBody toRequestBody(String value) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), value);
        return requestBody;
    }
}

4、图文混传(使用 MultipartBody.Part)

4.1接口定义

    @Multipart
    @POST("gather/vehicle")
    Call> uploadInfo(@Header("jwt-token") String token, @PartMap Map files, @Part MultipartBody.Part file);

4.2接口传参

private void uploadInfo(VehicleResponse response) {
        String token = SpUtil.getJwtToken(mContext);
        Map map = new HashMap<>();
        File file = new File(response.getImgUrl());
        RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpg"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);

        map.put("plateNo", toRequestBody(response.getPlateNo()));
        map.put("plateColor", toRequestBody(response.getPlateColor()));
        map.put("deviceId", toRequestBody(BizUtil.getImeiString(mContext)));
        map.put("longitude", toRequestBody(String.valueOf(response.getLongitude())));
        map.put("latitude", toRequestBody(String.valueOf(response.getLatitude())));
        map.put("address", toRequestBody(response.getAddress() + "_非空值"));
        map.put("gatherTime", toRequestBody(DateUtil.Long2String(response.getGatherTime(), "yyyy-MM-dd HH:mm:ss")));

        serviceApi.uploadInfo(token, map, body).enqueue(new HttpRequestCallback() {
            @Override
            public void onSuccess(VehicleResponse result) {
                super.onSuccess(result);
            }

            @Override
            public void onFailure(int status, String message) {
                super.onFailure(status, message);
            }
        });
    }

你可能感兴趣的:(Retrofit2)