Retrofit实际应用--->上传图片到服务器(获取上传进度)


引言

利用Retorfit和RxJava的结合实现将图片上传到服务器,并且获取图片上传的的进度。

具体实现

  • 首先定义网络请求接口
    //上传图片
    @Multipart
    @POST("everecords")
    Observable 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 params);

我们利用@Multipart注解,并且上传图片时也可以利用@Part注解传递一些其他参数,注解@PartMap我们可以一次上传多张图片。

  • 核心代码
        Map 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+"的上传进度:"+percentage);
                    }
                }));
       
        //提交到服务器
        RequestManager.retrofit()
                .create(RequestAPI.class)
                .uploadPicture(teacherId, eventId, childIds, commentIds, bodyMap)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(CommonResult value) {
                        Logger.d("请求成功----->图片上传");
                        //所有的图片上传成功后进行相应的处理
                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.e("请求失败---->图片上传:" + e.getMessage());
                    }
                    @Override
                    public void onComplete() {
                    }
                });
  • 下面时ProgressRequestBody类,构造RequestBody时用到的
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);
        }
    }
}

该类是获取图片上传进度的核心类。

文章写的非常简洁,有问题的大家可以留言探讨。

你可能感兴趣的:(Retrofit实际应用--->上传图片到服务器(获取上传进度))