13

如何使用改造在同一参数上添加多个图像/文件以及其他文本数据?

Single image is uploading perfectly using following interface
    @Multipart
    @POST("/users/updateProfile/")
    public void updateProfileWithImage(
                    @Part("user_id") TypedString first_name,
                    @Part ("image") TypedFile image, 
                    Callback<WebResponse> callback);
4

2 回答 2

12

您可以使用 @MultiPart Post 和@PartMap 作为参数

Map<String, TypedFile> files = new HashMap<String, TypedFile>();
files.put("my file number one", new TypedFile("image/jpg", new File(filename)));
files.put("my file number two", new TypedFile("image/jpg", new File(filename)));

apiInterface.updateProfileWithImage("first name here", files);

private interface ApiInterface{
    @Multipart
    @POST("/users/updateProfile/")
    Response updateProfileWithImage(
     @Part("user_id") TypedString first_name,
     @PartMap Map<String,TypedFile> Files
    );

}
于 2014-11-04T12:42:04.997 回答
12

Retrofit 2.0 + OkHttp 3

Interface declaration:

@POST("postpath")
Call<Void> upload(@Body MultipartBody filePart);

Creating MultiPartBody:

MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM);

then for each file(you can also add custom fields)

requestBodyBuilder.addFormDataPart("extraImage[]", "photo.jpg",
                            RequestBody.create(MediaType.parse("image/jpeg"), byteArrayOrFile));

and finally

api.upload(requestBodyBuilder.build());

P.S. you can add custom form fields (for example client.name) to the same form with

requestBodyBuilder.addFormDataPart("client[name]", null, RequestBody.create(MediaType.parse("text/plain"), name))

or

requestBodyBuilder.addFormDataPart("client[name]", name)) 

Retrofit 1.9:

You can use MultipartTypedOutput to post variable number of multi-part parameters.

In addition to François' answer, to post multiple images with the same / repeating field name(as an array) in retrofit you can use MultipartTypedOutput

Method signature:

@POST("/postpath")
SomeResponse upload(@Body MultipartTypedOutput output);

Usage:

MultipartTypedOutput multipartTypedOutput = new MultipartTypedOutput();
multipartTypedOutput.addPart("mainImage", new TypedFile("image/jpeg", mainImage));
multipartTypedOutput.addPart("extraImage[]", new TypedFile("image/jpeg", file1));
multipartTypedOutput.addPart("extraImage[]", new TypedFile("image/jpeg", file2));
upload(multipartTypedOutput);

Square brackets

Please note that some server side frameworks(Rails) typically require square brackets(i.e. extraImage[] instead of extraImage), others don't (Spring MVC).

于 2015-08-28T15:55:58.400 回答