不废话直接先导包:
这里我是用的jar包,你们可以网上直接找最新的,也可以找跟我版本差不多的
-
fun Upload(uploadFilePath: String?,
-
Uri: String?,
-
mMediaType: String?,
-
mResponseCallback: ResponseCallback) {
-
-
Log.i(
"TAG",
"uploadFilePath:" + uploadFilePath)
-
Log.i(
"TAG",
"Uri:" + Uri)
-
val uploadFile = File(uploadFilePath)
-
val client = OkHttpClient().newBuilder()
-
.readTimeout(
100, TimeUnit.SECONDS)
//读取超时
-
.connectTimeout(
60, TimeUnit.SECONDS)
//连接超时
-
.writeTimeout(
60, TimeUnit.SECONDS)
//写入超时
-
.connectionPool(ConnectionPool(
32,
-
5, TimeUnit.MINUTES))
//自定义连接池最大空闲连接数和等待时间大小,否则默认最大5个空闲连接
-
.build()
-
val mediaType = MediaType.parse(mMediaType)
-
val requestBody = RequestBody.create(mediaType, uploadFile)
//把文件与类型放入请求体
-
val body = MultipartBody.Builder()
-
.setType(MultipartBody.FORM)
-
.addFormDataPart(
"file", uploadFile.name, requestBody)
-
.build()
-
var request: Request? =
null
-
request = Request.Builder()
-
.url(Uri)
-
.post(body)
-
.build()
-
var call: Call? =
null
-
try {
-
call = client.newCall(request)
-
call.enqueue(
object : Callback {
-
override
fun onFailure(call: Call?, e: IOException) {
-
Log.i(
"TAG",
"failure upload!" + e.message)
-
mResponseCallback.onException(
"上传失败..." + e.message)
-
}
-
-
@Throws(IOException::class)
-
override
fun onResponse(call: Call?, response: Response) {
-
mResponseCallback.onResponse(response.body()!!.string())
-
}
-
})
-
-
}
catch (e1: IOException) {
-
e1.printStackTrace()
-
}
-
}
代码很简单,我先介绍一下参数
uploadFilePath :文件的上传地址,绝对地址,注意安卓10.0的文件权限Uri:服务器接收文件的地址mMediaType:资源类型,这个可以百度得到,比如视频是 video/mp4mResponseCallback:是一个回调
interface ResponseCallback { fun onResponse(string: String) fun onError(httpCode: Int?, errorBody: String?, throwable: Throwable?) fun onException(string: String) fun UploadProBar() }这个类看你们自己的交互可加可不加!
注意:我在使用这个类传大文件的时候出现通道破裂问题,但是小文件不会,这个问题是因为服务器默认限制了上传文件的大小
扩展:有些服务器会有token一说,那么如果有token的话,我们的配置就是这样的:
request = Request.Builder() .url(Uri) .post(body) .header(TokenName, Token) //后台所需要的token .build()tokenName是token的别名,Token就是服务器需要的token,看情况而定!
转载:https://blog.csdn.net/qq_36333309/article/details/111831765
查看评论