Retrofit2 上传图片进度显示

1上传的过程(handler中的计算需要注意,如果使用类型,每个参数都需要转换,不然就用一个较大数除以一个较小数,避免损失经度)

    @Multipart
    @POST("your url")
    Call uploadFile(@QueryMap Map map, @Part RequestBody file);

   private void upLoadFile(File file) {
        RequestBody resquestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        /**
         * 通过该行代码将RequestBody转换成特定的FileRequestBody
         */
        FileRequestBody requestBody = new FileRequestBody(resquestBody, callback);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
        Map maps = new HashMap<>();
        maps.put("id", "id参数");
        AppDataService.getInstance().uploadFile(maps, body).subscribe(new Consumer() {
            @Override
            public void accept(AppUpLoadFileBean appUpLoadFileBean) throws Exception {
                if (appUpLoadFileBean.getCode() == 200) {
                    LoadingUtil.dismiss();
                    wrokUrl = appUpLoadFileBean.getResponse_data();
                    LogUtils.e("进度条:" +wrokUrl);
                    ToastUtil.showLongToast(AppUploadWorkActivity.this, "上传成功");
                }
            }
        }, new Consumer() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                LogUtils.e("上传:" + throwable.getMessage());
            }
        });
    }


        RetrofitCallback callback = new RetrofitCallback() {
            @Override
            public void onSuccess(Call call, Response response) {
                //进度更新结束
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                //进度更新结束
            }

            @Override
            public void onLoading(final long total, final long progress) {
//                super.onLoading(total, progress);

                LogUtils.e("进度条:" + total + "  " + progress);
                //此处进行进度更新
                Message message = new Message();
                message.arg1 = (int) total;
                message.arg2 = (int) progress;
                message.what = 0;
                handler.sendMessage(message);

            }
        };
}

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                appUploadProgressTv.setText(((msg.arg2*100/msg.arg1))+"%");
            }
        }
    };

2激活相册操作

    private void goPhotoAlbum() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setType("video/*");//image/*为打开只有图片的系统相册(记得修改onActivityResult中的接收类型)
        startActivityForResult(intent, PictureConfig.CHOOSE_REQUEST);
    }
 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PictureConfig.CHOOSE_REQUEST) {
            //
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();

                String[] filePathColumn = {MediaStore.Video.Media.DATA};
            //String[] filePathColumn = {MediaStore.Images.Media.DATA};//图片接收类型
          
                Cursor cursor = getContentResolver().query(uri,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String videoPath = cursor.getString(columnIndex);
                cursor.close();
                LogUtils.e("v_name=" + videoPath);
                LogUtils.e("v_uri=" + uri);
                File file = new File(videoPath);
                //视频/头像封面
                Glide.with(this).load(videoPath).into(appUploadVideoIv);
              //  LoadingUtil.showLoading(this,"正在上传中...",false);
                upLoadFile(file);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

3封装请求体及回调


public final class FileRequestBody extends RequestBody {
    /**
     * 实际请求体
     */
    private RequestBody requestBody;
    /**
     * 上传回调接口
     */
    private RetrofitCallback callback;
    /**
     * 包装完成的BufferedSink
     */
    private BufferedSink bufferedSink;
    public FileRequestBody(RequestBody requestBody, RetrofitCallback callback) {
        super();
        this.requestBody = requestBody;
        this.callback = callback;
    }
    @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 (sink instanceof Buffer) {
            // Log Interceptor
            requestBody.writeTo(sink);
            return;
        }
        if (bufferedSink == null) {
            bufferedSink = Okio.buffer(sink(sink));
        }
        requestBody.writeTo(bufferedSink);
        bufferedSink.flush();
    }
    /**
     * 写入,回调进度接口
     * @param sink Sink
     * @return Sink
     */
    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;
                //回调
                callback.onLoading(contentLength, bytesWritten);
            }
        };
    }
}


public abstract class RetrofitCallback implements Callback {
    @Override
    public void onResponse(Call call, Response response) {
        if(response.isSuccessful()) {
            onSuccess(call, response);
        } else {
            onFailure(call, new Throwable(response.message()));
        }
    }
    public abstract void onSuccess(Call call, Response response);
    //用于进度的回调
    public abstract void onLoading(long total, long progress) ;
}

记录完毕。

你可能感兴趣的:(Retrofit2 上传图片进度显示)