Retrofit2 & RxJava2实现单文件和多文件上传,flutter面试题

本文详细介绍了如何使用Retrofit2和RxJava2在Android中实现单文件和多文件上传,包括Retrofit接口定义、MultipartBody构造、RequestBody自定义以及上传进度监听。提供了一个完整的代码实现,并提及了flutter面试相关知识点。
摘要由CSDN通过智能技术生成

FileUploadObserver fileUploadObserver) {

create(UploadFileApi.class)

.uploadFile(url, MultipartBuilder.filesToMultipartBody(files,

fileUploadObserver))

.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())

.subscribe(fileUploadObserver);

}

}

这个是Retrofit客户端类,获取它的单例然后去调用它的上传文件的方法,可以看到我这里封装了两个方法,uploadFile是上传单个文件,uploadFiles方法上传多个文件.

因为我们需要构造一个Retrofit对象,所以这里有一个RetrofitBuilder类:

/**

  • Retrofit构造器.

  • @author devilwwj

  • @since 2017/7/13

*/

public class RetrofitBuilder {

private static Retrofit retrofit;

public static synchronized Retrofit buildRetrofit() {

if (retrofit == null) {

Gson gson = new GsonBuilder().setDateFormat(“yyyy-MM-dd HH:mm:ss”).create();

GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create(gson);

retrofit = new Retrofit.Builder().client(OkHttpManager.getInstance())

.baseUrl(AppConfig.HTTP_SERVER)

.addConverterFactory(gsonConverterFactory)

.addCallAdapterFactory(RxJava2CallAdapterFactory.create())

.build();

}

return retrofit;

}

}

可以看到,想构造Retrofit对象是需要获取OkhttpClient实例的。

定义上传文件接口


/**

  • 上传API.

  • @author devilwwj

  • @since 2017/7/12

*/

public interface UploadFileApi {

String UPLOAD_FILE_URL = AppConfig.HTTP_SERVER + “file/upload”;

@POST

Observable uploadFile(@Url String url, @Body MultipartBody body);

}

这里就是Retrofit定义接口的形式,通过注解来表示各个参数,@POST表示发起post请求,@Url表示这是个请求地址,@Body表示这是请求体,关于Retrofit的各种注解的使用这里不多说,大家可以自行了解。

构造MultipartBody


上一步定义好了上传的接口,我们最终是要去构造MultipartBody&#

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值