class UploadHelper {
private val params = mutableMapOf<String, RequestBody>()
interface OnResultListener {
fun result(body: ResponseBody?)
}
inner class Builder(val params: Map<String, RequestBody>) {
fun sendRequest(
url: String,
listener: ProgressListener? = null,
resultListener: OnResultListener? = null
) {
// ProgressManager.getInstance()
// .addResponseListener(
// StringBuilder().append(NetWorkManager.instance.getBaseUrl())
// .append(url).toString(), listener
// )
try {
HandleFileManager.instance.create(CommonService::class.java)
.uploadFileMap(url, params).enqueue(object : retrofit2.Callback<ResponseBody> {
override fun onResponse(
call: Call<ResponseBody>,
response: Response<ResponseBody>
) {
resultListener?.result(response.body())
}
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
resultListener?.result(null)
}
})
} catch (e: Exception) {
resultListener?.result(null)
// ProgressManager.getInstance().notifyOnErorr(url, e)
}
}
}
/**
* 加入參数
* 依据传进来的Object对象来推断是String还是File类型的參数
*/
fun addParameter(key: String, o: Any): UploadHelper {
if (o is String) {
val body = o.toRequestBody("text/plain;charset=UTF-8".toMediaType())
params[key] = body
} else if (o is File) {
//注意不要使用byteArray 如果上传文件>90M 会报OOM内存溢出
//https://stackoverflow.com/questions/70091340/how-to-upload-large-file-to-the-server-using-retrofit-multipart
val body =
o.asRequestBody("multipart/form-data;charset=UTF-8".toMediaType())
// params["file\"; filename=\"" + o.name] = body
//注意上传多个文件一定要用 key 如果用"file\"只能上传一个文件
//HTTP的格式:
//name=key;filename=0.name xxxxxx
//name=key;filename=0.name xxxxxx
//......
params[key + "\"; filename=\"" + o.name + ""] = body
}
return this
}
//File.byteArray ktx 可直接转换
// fun changeByteArray(file: File): ByteArray {
// val fis = FileInputStream(file)
// file.readBytes()
// val swapStream = ByteArrayOutputStream()
// //将数据优先 存储到缓存区,最后在同步到stream 不要直接操作文件
// val buff = ByteArray(1024 * 4) //buff用于存放循环读取的临时数据
// var rc = 0
// while (fis.read(buff, 0, 100).also { rc = it } > 0) {
// swapStream.write(buff, 0, rc)
// }
// return swapStream.toByteArray()
// }
/**
* 构建RequestBody
*/
fun bulider(): Builder {
return Builder(params)
}
public fun clear() {
params.clear();
}
}
多文件上传
@Multipart
@POST
fun uploadFileMap(
@Url url: String,
@PartMap body: Map<String, @JvmSuppressWildcards RequestBody>
): Call<ResponseBody>