Android uses Retrofit form to upload multiple pictures
1.ApiService interface declaration method
1.1 In headers, you can add the business’s own header parameters.
@Multipart
@POST("api/uploadPic")
fun uploadFiles(
@HeaderMap headers: HashMap<String, String?>
@Part parts: List<MultipartBody.Part>
): Call<UploadResponse>
1.2 Create retrofit and initiate a request
Retrofit retrofit=new Retrofit.Builder()
.baseUrl("http:xxx")
.addConverterFactory(GsonConverterFactory.create())
.build();
The server requires the file to be placed in the body in the form of an array, and the key is files. value file array.
val service = retrofit.create(ApiService::class.java)
val body = Utils.picToRequestBody("files",list)
val headers = getCommonParams()
service.uploadFiles(headers, body).enqueue(object : Callback<UploadResponse> {
override fun onResponse(
call: Call<UploadResponse>,
response: Response<UploadResponse>
) {
}
override fun onFailure(call: Call<UploadResponse>, t: Throwable) {
}
})
1.3 Tools
fun picToRequestBody(name: String, images: MutableList<Image>): List<MultipartBody.Part> {
val parts = arrayListOf<MultipartBody.Part>()
//多个图片文件
for (image in images) {
val file = File(image.path)
val requestBody = RequestBody.create(MediaType.parse("*/*"), file)
val part =
MultipartBody.Part.createFormData(name, file.name, requestBody)
parts.add(part)
}
return parts
}
Result uploaded successfully
Reference article:
https://wenku.baidu.com/view/c571691264ec102de2bd960590c69ec3d5bbdb05.html