Retrofit Upload multiple files and parameters

放在前面的图


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

代码:
<code>
apiService:

@Multipart
@POST
Observable<String> uploadFile(@Url String url, @Part List<MultipartBody.Part > files,@PartMap Map<String, RequestBody> params);

ApiInteractor:

Subscription uploadFile(String url, List<MultipartBody.Part > files, Map<String, RequestBody> param, BaseSubscribe<String> subsribe);

ApiInteractorImpl:

/**
 * 文件上传
 * @param url
 * @param param
 * @param subsribe
 * @return
 */
@Override
public Subscription uploadFile(String url, List<MultipartBody.Part > files, Map<String, RequestBody> param, BaseSubscribe<String> subsribe) {
    Observable<String> 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<String,RequestBody> map = new HashMap<>();//参数
    List<MultipartBody.Part> mList = new ArrayList<>();//文件
    map.put("后台需要的字段key",createPartFromString("你的参数值"));mList.add(prepareFilePart("resource",file2));
    Subscription uploadFile = api.uploadFile(ConstantApi.uploadMp4AAC,mList,map, new BaseSubscribe<String>() {
        @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);
    }
}

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

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

参考:

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

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,626评论 25 709
  • 是Square公司开发的一款针对Android网络请求的框架,Retrofit2底层基于OkHttp实现的,现在已...
    Android开发__落岑阅读 1,836评论 0 2
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,269评论 19 139
  • https://mp.weixin.qq.com/s?__biz=MzI1NDg4MTIxMw==&mid=224...
    g0阅读 266评论 0 0
  • 小菜17阅读 350评论 0 1