Retrofit Upload multiple files and parameters

放在前面的图

Retrofit Upload multiple files and parameters_第1张图片

Retrofit 的介绍以及基本使用 这里不再说明。
关于多文件上传 以及上传文件的同时携带多个参数说明
网上涉及到的不是太多。

代码:

apiService:

@Multipart
@POST
Observable uploadFile(@Url String url, @Part List files,@PartMap Map params);

ApiInteractor:

Subscription uploadFile(String url, List files, Map param, BaseSubscribe subsribe);

ApiInteractorImpl:

/**
 * 文件上传
 * @param url
 * @param param
 * @param subsribe
 * @return
 */
@Override
public Subscription uploadFile(String url, List files, Map param, BaseSubscribe subsribe) {
    Observable uploadFile = apiService.uploadFile(url,files,param);
    Subscription subscription = uploadFile.subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .retryWhen(new RetryWithDelay(App.getContext(), startTimeOut, maxTimeOut, SECONDS))
        .onErrorReturn(throwable -> null)
        .subscribe(subsribe);
    return subscription;
}

Activity 中代码:

private void upload() {
    File file2 = new File(cacheVideo + "girl.jpg");
    Map map = new HashMap<>();//参数
    List mList = new ArrayList<>();//文件
    map.put("后台需要的字段key",createPartFromString("你的参数值"));mList.add(prepareFilePart("resource",file2));
    Subscription uploadFile = api.uploadFile(ConstantApi.uploadMp4AAC,mList,map, new BaseSubscribe() {
        @Override
        public void onSuccess(String result) {
            Log.d("上传返回结果是", "onSuccess: "+result);
        }
    });
    subscription.add(uploadFile);
}

public static final String MULTIPART_FORM_DATA = "multipart/form-data";

private RequestBody createPartFromString(String descriptionString) {
    return RequestBody.create(
        MediaType.parse(MULTIPART_FORM_DATA), descriptionString);
}

private MultipartBody.Part prepareFilePart(String partName, File fileName) {
    RequestBody requestFile = RequestBody.create(MediaType.parse(MULTIPART_FORM_DATA),fileName);
    UploadRequestBody uploadRequestBody=new     UploadRequestBody(requestFile, new UploadRequestBody.Listener()     {
    @Override
    public void onRequestProgress(long bytesWritten, long contentLength) {
        Log.e("上传进度","file1:"+contentLength+":"+bytesWritten);
    }
});
    return MultipartBody.Part.createFormData(partName, fileName.getName(), uploadRequestBody);
}

重写RequestBody 监听回调

public class UploadRequestBody extends RequestBody {

    protected RequestBody delegate;
    protected Listener listener;

    protected CountingSink countingSink;

    public UploadRequestBody(RequestBody delegate, Listener listener) {
        this.delegate = delegate;
        this.listener = listener;
    }

    @Override
    public MediaType contentType() {
        return delegate.contentType();
    }

    @Override
    public long contentLength() {
        try {
            return delegate.contentLength();
        } catch (IOException e) {
           e.printStackTrace();
        }
        return -1;
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {

        countingSink = new CountingSink(sink);
        BufferedSink bufferedSink = Okio.buffer(countingSink);

        delegate.writeTo(bufferedSink);

        bufferedSink.flush();
    }

    protected final class CountingSink extends ForwardingSink {

        private long bytesWritten = 0;

        public CountingSink(Sink delegate) {
            super(delegate);
        }

        @Override
        public void write(Buffer source, long byteCount) throws IOException {
            super.write(source, byteCount);

            bytesWritten += byteCount;
            listener.onRequestProgress(bytesWritten, contentLength());
        }

    }

    public interface Listener {
        void onRequestProgress(long bytesWritten, long contentLength);
    }
}


// ==================至此 基本结束 Retrofit 同时上传多个参数 和 文件结束

主要是 @后面的关键字段我们可能不是太清楚 或者很少用到

参考:

https://square.github.io/retrofit/

https://futurestud.io/tutorials/retrofit-2-how-to-upload-files-to-server欢迎交流指正学习~

你可能感兴趣的:(Retrofit Upload multiple files and parameters)