RxRetrofit - 終極封裝 - 深入淺出 & 檔案上傳

wzgiceman發表於2016-12-24

背景

在實際運用中上傳是一個必不可少的功能,所以我們在封裝二的基礎上加入上傳的功能,同時需要附帶上傳進度!


效果

RxRetrofit - 終極封裝 - 深入淺出 & 檔案上傳
這裡寫圖片描述


實現

1.定義service介面

注意:Multipart是指定大檔案上傳過程中的標示,一般上傳圖片的過程中我們需要附帶資訊,所以我們需要用到@part指定傳遞的數值,MultipartBody.Part是指定傳遞的檔案;

    /*上傳檔案*/
    @Multipart
    @POST("AppYuFaKu/uploadHeadImg")
    Observable<BaseResultEntity<UploadResulte>> uploadImage(@Part("uid") RequestBody uid, @Part("auth_key") RequestBody  auth_key,                                                         @Part MultipartBody.Part file);複製程式碼

2.加入進度條

retrofit是基於okhttp的處理,所以我們可以自定義RequestBody,複寫writeTo(BufferedSink sink)方法,得到傳遞的進度資料

public class ProgressRequestBody extends RequestBody {
    //實際的待包裝請求體
    private final RequestBody requestBody;
    //進度回撥介面
    private final UploadProgressListener progressListener;
    //包裝完成的BufferedSink
    private BufferedSink bufferedSink;

    public ProgressRequestBody(RequestBody requestBody, UploadProgressListener progressListener) {
        this.requestBody = requestBody;
        this.progressListener = progressListener;
    }
    /**
     * 重寫呼叫實際的響應體的contentType
     * @return MediaType
     */
    @Override
    public MediaType contentType() {
        return requestBody.contentType();
    }
    /**
     * 重寫呼叫實際的響應體的contentLength
     * @return contentLength
     * @throws IOException 異常
     */
    @Override
    public long contentLength() throws IOException {
        return requestBody.contentLength();
    }
    /**
     * 重寫進行寫入
     * @param sink BufferedSink
     * @throws IOException 異常
     */
    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        if (null == bufferedSink) {
            bufferedSink = Okio.buffer(sink(sink));
        }
        requestBody.writeTo(bufferedSink);
        //必須呼叫flush,否則最後一部分資料可能不會被寫入
        bufferedSink.flush();
    }
    /**
     * 寫入,回撥進度介面
     * @param sink Sink
     * @return Sink
     */
    private Sink sink(Sink sink) {
        return new ForwardingSink(sink) {
            //當前寫入位元組數
            long writtenBytesCount = 0L;
            //總位元組長度,避免多次呼叫contentLength()方法
            long totalBytesCount = 0L;
            @Override
            public void write(Buffer source, long byteCount) throws IOException {
                super.write(source, byteCount);
                //增加當前寫入的位元組數
                writtenBytesCount += byteCount;
                //獲得contentLength的值,後續不再呼叫
                if (totalBytesCount == 0) {
                    totalBytesCount = contentLength();
                }
                Observable.just(writtenBytesCount).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {
                        progressListener.onProgress(writtenBytesCount, totalBytesCount);
                    }
                });
            }
        };
    }
}複製程式碼

3.自定義介面,回撥progress進度

public interface UploadProgressListener {
    /**
     * 上傳進度
     * @param currentBytesCount
     * @param totalBytesCount
     */
    void onProgress(long currentBytesCount, long totalBytesCount);
}複製程式碼

4.建立RequestBody物件,加入進度

 File file=new File("/storage/emulated/0/Download/11.jpg");
      RequestBody requestBody=RequestBody.create(MediaType.parse("image/jpeg"),file);
      MultipartBody.Part part= MultipartBody.Part.createFormData("file_name", file.getName(), new ProgressRequestBody(requestBody,
              new UploadProgressListener() {
          @Override
          public void onProgress(long currentBytesCount, long totalBytesCount) {
              tvMsg.setText("提示:上傳中");
              progressBar.setMax((int) totalBytesCount);
              progressBar.setProgress((int) currentBytesCount);
          }
      }));複製程式碼

5.傳遞附帶資訊

封裝二中post請求的方式一樣,我們需要繼承baseentity,複寫裡面的方法,然後設定需要傳遞的引數,因為是測試介面,所以我的引數直接寫死在entity裡面,part檔案動態指定


/**
 * 上傳請求api
 * Created by WZG on 2016/10/20.
 */

public class UplaodApi extends BaseEntity {
    /*需要上傳的檔案*/
    private MultipartBody.Part part;


    public UplaodApi(HttpOnNextListener listener, RxAppCompatActivity rxAppCompatActivity) {
        super(listener, rxAppCompatActivity);
        setShowProgress(true);
    }

    public MultipartBody.Part getPart() {
        return part;
    }

    public void setPart(MultipartBody.Part part) {
        this.part = part;
    }

    @Override
    public Observable getObservable(HttpService methods) {
        RequestBody uid= RequestBody.create(MediaType.parse("text/plain"), "4811420");
        RequestBody key = RequestBody.create(MediaType.parse("text/plain"), "21f8d9bcc50c6ac1ae1020ce12f5f5a7");
        return methods.uploadImage(uid,key,getPart());
    }
}複製程式碼

6.post請求處理

請求和封裝二中的請求一樣,通過傳遞一個指定的HttpOnNextListener 物件來回撥來監聽結果資訊,一一對應


  private void uploadeDo(){
      File file=new File("/storage/emulated/0/Download/11.jpg");
      RequestBody requestBody=RequestBody.create(MediaType.parse("image/jpeg"),file);
      MultipartBody.Part part= MultipartBody.Part.createFormData("file_name", file.getName(), new ProgressRequestBody(requestBody,
              new UploadProgressListener() {
          @Override
          public void onProgress(long currentBytesCount, long totalBytesCount) {
              tvMsg.setText("提示:上傳中");
              progressBar.setMax((int) totalBytesCount);
              progressBar.setProgress((int) currentBytesCount);
          }
      }));
      UplaodApi uplaodApi = new UplaodApi(httpOnNextListener,this);
      uplaodApi.setPart(part);
      HttpManager manager = HttpManager.getInstance();
      manager.doHttpDeal(uplaodApi);
  }


    /**
     * 上傳回撥
     */
    HttpOnNextListener httpOnNextListener=new HttpOnNextListener<UploadResulte>() {
        @Override
        public void onNext(UploadResulte o) {
            tvMsg.setText("成功");
            Glide.with(MainActivity.this).load(o.getHeadImgUrl()).skipMemoryCache(true).into(img);
        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
            tvMsg.setText("失敗:"+e.toString());
        }

    };複製程式碼

結構

RxRetrofit - 終極封裝 - 深入淺出 & 檔案上傳


終極封裝專欄

RxRetrofit深入淺出-終極封裝專欄


原始碼

傳送門-原始碼地址


建議

如果你對這套封裝有任何的問題和建議歡迎加入QQ群告訴我!

相關文章