Android使用 Retrofit 2.X 上传多文件和多表单示例
retrofit post请求上传表单和文件最重要的就是就是去构建RequestBody,今天为大家带来一种超级简单的上传方式
Body方式:
1、Retrofit接口RetrofitInterface
@POST(URLConstant.URL_PATH) Flowable<UploadImgBean> upload(@Body RequestBody Body);
2、Retrofit的配置
private static RetrofitInterface getRetrofitInterface(String baseUrl) { if (retrofitInterface == null) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) // .addConverterFactory(ScalarsConverterFactory.create()) //string .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); retrofitInterface = retrofit.create(RetrofitInterface.class); } return retrofitInterface; }
3、构建body
public static Flowable<UploadImgBean> upload(List<File> fileList) { //构建body //addFormDataPart()第一个参数为表单名字,这是和后台约定好的 MultipartBody.Builder builder = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("username", "name") .addFormDataPart("phone", "phone") //注意,file是后台约定的参数,如果是多图,file[],如果是单张图片,file就行 for (File file : fileList) { //这里上传的是多图 builder.addFormDataPart("file[]", file.getName(), RequestBody.create(MediaType.parse("image/*"), file)); } RequestBody requestBody = builder.build(); return getRetrofitInterface(URLConstant.URL_BASE).upload(requestBody); }
4、开始执行上传
HttpUtils.upload(mUploadFileList) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new DisposableSubscriber<UploadImgBean>() { @Override public void onNext(UploadImgBean uploadImgBean) { Log.i(TAG, "onNext: " ); } } @Override public void onError(Throwable throwable) { Log.i(TAG, "onError: --->" + throwable.getMessage()); } @Override public void onComplete() { Log.i(TAG, "onComplete: "); } });
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)