val result = RxHttp.postForm(“/service/…”)
.add(“key”, “value”)
.addPart(context, “file”, uri)
.awaitString() //awaitXxx系列方法是挂断方法
//RxJava
RxHttp.postForm(“/service/…”)
.add(“key”, “value”)
.addPart(context, “file”, uri)
.asString()
.subscribe({
//成功回调
}, {
//异常回调
})
复制代码
同样的,RxHttp内部提供了一系列addPart
方法供大家选择,列出几个常用的,如下:
//添加单个Uri对象
addPart(Context, String, Uri)
//添加多个Uri对象,每个Uri对应相同的key
addParts(Context,String, List<? extends Uri> uris)
//添加多个Uri对象,每个Uri对应不同的key
addParts(Context context, Map<String, ? extends Uri> uriMap)
//等等其它addPart方法
复制代码
3.2、带进度上传
老规矩,看看Android 10之前是如何监听上传进度的,如下:
//kotlin 协程
val result = RxHttp.postForm(“/service/…”)
.add(“key”, “value”)
.addFile(“file”, new File(“xxx/1.jpg”))
.upload(this) {//this为当前协程CoroutineScope对象,用于控制回调线程
//上传进度回调,0-100,仅在进度有更新时才会回调
val currentProgress = it.getProgress() //当前进度 0-100
val currentSize = it.getCurrentSize() //当前已上传的字节大小
val totalSize = it.getTotalSize() //要上传的总字节大小
}
.awaitString() //awaitXxx系列方法是挂断方法
//RxJava
RxHttp.postForm(“/service/…”)
.add(“key”, “value”)
.addFile(“file”, new File(“xxx/1.jpg”))
.upload(AndroidSchedulers.mainThread()) {
//上传进度回调,0-100,仅在进度有更新时才会回调
int currentProgress = it.getProgress() //当前进度 0-100
long currentSize = it.getCurrentSize() //当前已上传的字节大小
long totalSize = it.getTotalSize() //要上传的总字节大小
}
.asString()
.subscribe({
//成功回调
}, {
//异常回调
})
复制代码
相比于单纯的上传文件,我们仅需额外调用upload
操作符,传入线程调度器及进度回调即可。
同样的,对于Andorid 10,我们仅需要将File对象换成Uri对象即可,如下:
val context = getContext(); //获取上下文对象
//获取Uri对象,这里为了方便,随便写了一个Downlaod目录下的Uri地址
val uri = Uri.parse(“content://media/external/downloads/13417”)
//kotlin 协程
val result = RxHttp.postForm(“/service/…”)
.add(“key”, “value”)
.addPart(context, “file”, uri)
.upload(this) {//this为当前协程CoroutineScope对象,用于控制回调线程
//上传进度回调,0-100,仅在进度有更新时才会回调
val currentProgress = it.getProgress() //当前进度 0-100
val currentSize = it.getCurrentSize() //当前已上传的字节大小
val totalSize = it.getTotalSize() //要上传的总字节大小
}
.awaitString() //awaitXxx系列方法是挂断方法
//RxJava
RxHttp.postForm(“/service/…”)
.add(“key”, “value”)
.addPart(context, “file”, uri)
.upload(AndroidSchedulers.mainThread()) {
//上传进度回调,0-100,仅在进度有更新时才会回调
int currentProgress = it.getProgress() //当前进度 0-100
long currentSize = it.getCurrentSize() //当前已上传的字节大小
long totalSize = it.getTotalSize() //要上传的总字节大小
}
.asString()
.subscribe({
//成功回调
}, {