Android Retrofit使用MultipartBody

July 4, 2019

指定 RequestBody 上传的文件路径

1
val requestBody = RequestBody.create(MediaType.parse("file/*"), File(filepath))

构建 MultipartBody 消息体

1
2
3
4
5
val body = MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("convertType", type)
        .addFormDataPart("file", fileName, requestBody)
        .build()

发出请求即可

1
2
3
4
val request = Request.Builder()
        .url(urlString)
        .post(body)
        .build()