retrofit上传获取文件上传进度

1.重写CallBack接口

public abstract class UploadCallback<T> implements Callback<T> {
    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (response.isSuccessful()) {
            onSuccess(call,response);
        }else {
            onFailure(call,new Throwable(response.message()));
        }
    }
    public abstract void onSuccess(Call<T> call , Response<T> response);

    /*
    * 回调方法获取上传的进度
    * */
    public void onLoading(long total , long progress){
    }
}

2.重写RequestBody请求体

public  class UploadRequestBody<T> extends RequestBody{

    /*
    * 请求体
    * */
    private RequestBody requestBody;

    /*
    * 上传回调
    * */
    private UploadCallback<T> uploadCallback;
    private BufferedSink bufferedSink;


    public UploadRequestBody(RequestBody requestBody, UploadCallback<T> uploadCallback) {
        this.requestBody = requestBody;
        this.uploadCallback = uploadCallback;
    }
    @Override
    public long contentLength() throws IOException {
        return requestBody.contentLength();
    }



    @Override
    public MediaType contentType() {
        return requestBody.contentType();
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        if(bufferedSink == null){
            //包装
            bufferedSink = Okio.buffer(sink(sink));
        }
        //写入
        requestBody.writeTo(bufferedSink);
        //必须调用flush,否则最后一部分数据可能不会被写入
        bufferedSink.flush();
    }
    /**
     * 写入,回调进度接口
     * @param sink
     * @return
     */
    private Sink sink(Sink sink){
        return new ForwardingSink(sink) {
            //当前写入字节数
            long bytesWritten = 0L;
            //总字节长度,避免多次调用contentLength()方法
            long contentLength = 0L;

            @Override
            public void write(Buffer source, long byteCount) throws IOException {
                super.write(source, byteCount);
                if(contentLength == 0){
                    //获得contentLength的值,后续不再调用
                    contentLength = contentLength();
                }
                //增加当前写入的字节数
                bytesWritten += byteCount;
                //回调
                uploadCallback.onLoading(contentLength, bytesWritten);
            }
        };
    }
}
3.上传图片测试

 private void imgFilesParts(List<String> allImg,UploadCallback<UploadResultBean> callback){
        MultipartBody.Part[] parts = new MultipartBody.Part[allImg.size()];
        for (int i = 0; i < allImg.size(); i++) {
            String url = allImg.get(i);
            File file = new File(url);
            String imageName = url.substring(url.lastIndexOf("/") + 1);
            RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            //创建UploadRequestBody请求体
            UploadRequestBody requestBody = new UploadRequestBody(requestFile, callback);
            parts[i] = MultipartBody.Part.createFormData("file",imageName, requestBody);
        }
         Call<UploadResultBean> syncImageFile = service.getSyncImageFile(ApiManger.getBasicHeader(5, null), parts);
          syncImageFile.enqueue(callback);
    }
4.UI线程调用

imgFilesParts(allImgPath, new UploadCallback<UploadResultBean>() {
                @Override
                public void onSuccess(Call<UploadResultBean> call, Response<UploadResultBean> response) {
                    if (response.isSuccessful()) {
                        UploadResultBean body = response.body();
                        String message = body.getMessage();
                        int status = body.getStatus();
                      
                    }
                }

                @Override
                public void onFailure(Call<UploadResultBean> call, Throwable t) {
                   
                }

                @Override
                public void onLoading(long total, long progress) {
                    Log.d("loading", "onLoading: "+ total+"-------->"+progress);
                }
            });


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 ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值