http接口封装
首先是根据自己选用的网络框架进行文件上传的接口封装
@Multipart
@POST("/FreshCabinet/a/ly/app/uploadImg")
fun uploadReserveSampleImgAsync(@PartMap params: HashMap<String, RequestBody?>?)
:Deferred<ResponseWrapper<UploadImgBackBean>>
suspend fun uploadReserveSampleImg(params: HashMap<String, RequestBody?>?) =
getApiService().uploadReserveSampleImgAsync(params).await()
文件上传工具类
我们可以通过封装一个参数处理的工具类,帮我们去识别传入的是普通参数类型还是文件类型:
class UploadHelper private constructor() {
fun addParameter(key: String, o: Any): UploadHelper {
var body: RequestBody? = null
if (o is String) {
body = RequestBody.create("text/plain;charset=UTF-8".toMediaTypeOrNull(), o)
} else if (o is File) {
body = RequestBody.create(
"multipart/form-data;charset=UTF-8".toMediaTypeOrNull(), o
)
}
params[key] = body
return this
}
fun builder(): HashMap<String, RequestBody?> {
return params
}
fun clear() {
params.clear()
}
companion object {
@Volatile
private var mInstance: UploadHelper? = null
lateinit var params: HashMap<String, RequestBody?>
val instance: UploadHelper?
get() {
if (mInstance == null) {
synchronized(UploadHelper::class.java) {
if (mInstance == null) mInstance = UploadHelper()
params = HashMap()
}
}
return mInstance
}
}
}
页面调用处理
在页面上可以直接使用工具类将相关文件以及参数添加进参数数组中
val helper = UploadHelper.instance
helper?.clear()
helper?.addParameter("img", File(imgUrl))
val params = helper?.builder()
cabinetViewModel.uploadImg(params, {},
{ loadingDialog.show() },
{ loadingDialog.dismiss() })
|