1. 程式人生 > >retrofit上傳獲取檔案上傳進度

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