怎么在Android中利用Retrofit 2.X 上传文件?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
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: "); } });
关于怎么在Android中利用Retrofit 2.X 上传文件问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注编程网行业资讯频道了解更多相关知识。