如下图所示,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 ):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)
fun getTextRequestBody(txt:String) = RequestBody.create(MediaType.parse("text/plain"), txt)
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)
|