如下图所示,uploadFile是文件,relationId、type这种是提交时附带的参数

1
2
3
4
5
6
7
@Multipart
@POST("api/common/upload/user/pic")
suspend fun uploadAvatar(
@Part("relationId") relationId :String,
@Part("type") type :String,
@Part uploadFile :MultipartBody.Part //此处part不能设置value,提交名称在下面设置
):Response<BaseDTO<*>>

如果retrofit添加了.addConverterFactory(GsonConverterFactory.create()),提交时会当做json提交,如果直接在接口中定义@Part("relationId") relationId :String,contentType会是application-json,提交的字符串会多拼上一堆双引号

将接口修改为:

1
2
3
4
5
6
7
@Multipart
@POST("api/common/upload/user/pic")
suspend fun uploadAvatar(
@Part("relationId") relationId :RequestBody,
@Part("type") type :RequestBody,
@Part uploadFile :MultipartBody.Part
):Response<BaseDTO<*>>

参数用下面方式生成即可:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 文件
fun fileToMultiPart(file: File,name:String=uploadFile):MultipartBody.Part {
val requestBody = RequestBody.create(MultipartBody.FORM, file)
val part = MultipartBody.Part.createFormData(name, file.name, requestBody) //提交名称在这设置
return part
}
// 图片
fun getImgRequestBody(file:File) = RequestBody.create(MediaType.parse("image/*"), file)
// 字符串,上面的接口中 type和relationId用这个生成requestBody
fun getTextRequestBody(txt:String) = RequestBody.create(MediaType.parse("text/plain"), txt)

/*----------- 下面都是生成json的requestBody---------------------*/
fun getRequestBody(params: Map<String, Any>): RequestBody {
return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JSONObject(params).toString())
}

fun getRequestBody(jsonObject: JSONObject): RequestBody {
return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString())
}

fun getRequestBody(json: String): RequestBody {
return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json)
}

fun getRequestBody(`object`: Any): RequestBody {
val json = Gson().toJson(`object`)
return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json)