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);
                }
            });


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页