Retrofit實(shí)際應(yīng)用--->上傳圖片到服務(wù)器(獲取上傳進(jìn)度)


引言

利用Retorfit和RxJava的結(jié)合實(shí)現(xiàn)將圖片上傳到服務(wù)器,并且獲取圖片上傳的的進(jìn)度。

具體實(shí)現(xiàn)

  • 首先定義網(wǎng)絡(luò)請求接口
    //上傳圖片
    @Multipart
    @POST("everecords")
    Observable<CommonResult> uploadPicture(@Part("teacher_id") long teacher_id,
                                           @Part("event_id") long event_id,
                                           @Part("child_ids") String child_ids,
                                           @Part("eve_tags") String eve_tags,
                                           @PartMap Map<String, RequestBody> params);

我們利用@Multipart注解,并且上傳圖片時(shí)也可以利用@Part注解傳遞一些其他參數(shù),注解@PartMap我們可以一次上傳多張圖片。

  • 核心代碼
        Map<String, RequestBody> bodyMap = new HashMap<>();
        File file = new File(path);
        bodyMap.put("assets" + 0 + "\"; filename=\"" + file.getName(), new ProgressRequestBody(file, new ProgressRequestBody.UploadCallbacks() {
                    @Override
                    public void onProgressUpdate(int percentage,long id) {
                        Logger.d("圖片"+pictureId+"的上傳進(jìn)度:"+percentage);
                    }
                }));
       
        //提交到服務(wù)器
        RequestManager.retrofit()
                .create(RequestAPI.class)
                .uploadPicture(teacherId, eventId, childIds, commentIds, bodyMap)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CommonResult>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(CommonResult value) {
                        Logger.d("請求成功----->圖片上傳");
                        //所有的圖片上傳成功后進(jìn)行相應(yīng)的處理
                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.e("請求失敗---->圖片上傳:" + e.getMessage());
                    }
                    @Override
                    public void onComplete() {
                    }
                });
  • 下面時(shí)ProgressRequestBody類,構(gòu)造RequestBody時(shí)用到的
public class ProgressRequestBody extends RequestBody {
    private File mFile;
    private String mPath;
    private UploadCallbacks mListener;
    private long id;
    private static final int DEFAULT_BUFFER_SIZE = 2048;

    public interface UploadCallbacks {
        void onProgressUpdate(int percentage,long id);
    }

    public ProgressRequestBody(long id,final File file, final UploadCallbacks listener) {
        this.id = id;
        mFile = file;
        mListener = listener;
    }
    public ProgressRequestBody(final File file, final UploadCallbacks listener) {
        this.id = id;
        mFile = file;
        mListener = listener;
    }


    @Override
    public MediaType contentType() {
        // i want to upload only images
        return MediaType.parse("image/*");
    }

    @Override
    public long contentLength() throws IOException {
        return mFile.length();
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        long fileLength = mFile.length();
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        FileInputStream in = new FileInputStream(mFile);
        long uploaded = 0;

        try {
            int read;
            Handler handler = new Handler(Looper.getMainLooper());
            while ((read = in.read(buffer)) != -1) {
                uploaded += read;
                sink.write(buffer, 0, read);
                // update progress on UI thread
                handler.post(new ProgressUpdater(uploaded, fileLength));
            }
        } finally {
            in.close();
        }
    }

    private class ProgressUpdater implements Runnable {
        private long mUploaded;
        private long mTotal;

        public ProgressUpdater(long uploaded, long total) {
            mUploaded = uploaded;
            mTotal = total;
        }

        @Override
        public void run() {
            mListener.onProgressUpdate((int) (100 * mUploaded / mTotal),id);
        }
    }
}

該類是獲取圖片上傳進(jìn)度的核心類。

文章寫的非常簡潔,有問題的大家可以留言探討。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容