Retrofit2 使用@Multipart上传文件

1、上传单个文件

1.1定义接口

 
    @Multipart
    @POST("uploadImgs")
    Call<HttpBaseResult<List<PicResultData>>> 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<List<PicResultData>>() {

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

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

    }

2、上传多个文件

2.1定义接口

   @Multipart
    @POST("uploadImgs")
    Call<HttpBaseResult<List<PicResultData>>> uploadMultiImgs(@PartMap Map<String, RequestBody> maps);

2.2接口传参

   public void uploadImgs(Object pcObj, List<String> imgStrs) {
        Map<String, RequestBody> 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<List<PicResultData>>() {

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

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

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

3.1定义接口

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

3.2接口传参

 private void uploadInfo(VehicleResponse response) {
        String token = SpUtil.getJwtToken(mContext);
        Map<String, RequestBody> 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<VehicleResponse>() {
            @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<HttpBaseResult<VehicleResponse>> uploadInfo(@Header("jwt-token") String token, @PartMap Map<String, RequestBody> files, @Part MultipartBody.Part file);

4.2接口传参

private void uploadInfo(VehicleResponse response) {
        String token = SpUtil.getJwtToken(mContext);
        Map<String, RequestBody> 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<VehicleResponse>() {
            @Override
            public void onSuccess(VehicleResponse result) {
                super.onSuccess(result);
            }

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

5、多文件上传(使用 List<MultipartBody.Part>)

5.1、定义接口:

 @Multipart
 @POST("yj-kecis-server/kecis/file/commonUpload/batch")
 suspend fun commonUploadFileBatch(@Part parts: List<MultipartBody.Part>): HttpBaseResult<List<HttpMultiFileResponse>>

5.2、接口传参:

 private fun uploadFiles(localFiles : List<String>) {
        val parts: MutableList<MultipartBody.Part> = mutableListOf()
        localFiles?.forEach { filePath ->
            val file = File(filePath)
            val requestBody: RequestBody = RequestBody.create(okhttp3.MediaType.parse("application/octet-stream"), file)
            val part = MultipartBody.Part.createFormData("files", file.name, requestBody)
            
            parts.add(part)//循环添加多个文件
        }
        
        //其他参数
        parts.add( MultipartBody.Part.createFormData( "moduleName", INCIDENT_ANNEX_SERVER_FOLDER) )
        
        httpLaunch(false,
            request = { HttpServicesFactory.httpApi.commonUploadFileBatch(parts) },
            onSuccess = { fileResponse -> 
            ...
            },
            onError = { msg ->
                showToast("附件上传失败$msg")
            }
        )
    }
  • 25
    点赞
  • 77
    收藏
    觉得还不错? 一键收藏
  • 14
    评论
Retrofit2是一个流行的Android网络框架,可以通过注解和动态代理来简化网络请求的步骤。在使用Retrofit2进行文件上传时,可以使用@Multipart注解和@PartMap注解来实现多文件上传。\[1\] 具体的实现步骤如下: 1. 在Retrofit接口中使用@Multipart注解标记该方法为多部分请求。 2. 使用@POST注解指定上传文件的URL。 3. 使用@PartMap注解将文件参数以Map的形式传递给方法。 4. 在Map中,键是参数的名称,值是RequestBody类型的文件内容。 例如,可以使用以下代码来实现文件上传: ``` @Multipart @POST("upload") Observable<String> uploadFiles(@PartMap Map<String, RequestBody> files); ``` 其中,files是一个Map,键是文件参数的名称,值是RequestBody类型的文件内容。 Retrofit2之所以被广泛使用,是因为它能够根据注解封装网络请求,并通过转化器将原始的HTTP响应内容转化为我们需要的对象。这使得使用Retrofit2非常方便。\[2\]\[3\] #### 引用[.reference_title] - *1* *3* [Retrofit2 multpart多文件上传详解](https://blog.csdn.net/jdsjlzx/article/details/51649382)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [retrofit2上传文件总结](https://blog.csdn.net/u011323666/article/details/52288753)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值