使用Retrofit是否可以将单个项目作为multipart传递?

3
 @Multipart
@POST("/api/add-deal/")
public void addDeal(@Body Deal deal, @Part("image")TypedFile image,Callback<Response> callback);

我想将只有图像作为multipart发送,其余内容保持不变。是否有可能?即使我尝试在我的Deal模型中添加TypedFile,但无法注释@part。

3个回答

2

是的,可以使用哈希映射和Partmap注释来实现。例如:

    @Multipart
    @POST("/api/add-deal/")
    Call<Response> addDeal(@PartMap 
    HashMap<String, RequestBody> hashMap);

在hashMap中,您可以将多个url参数添加为键,并使用RequestBody类类型设置您的值。请查看如何将字符串和图像转换为RequestBody。
    public static RequestBody ImageToRequestBody(File file) { //for image file to request body
           return RequestBody.create(MediaType.parse("image/*"),file);
    }

    public static RequestBody StringToRequestBody(String string){ // for string to request body
           return RequestBody.create(MediaType.parse("text/plain"),string);
    }

向哈希表中添加参数 -

    hashMap.put("photo",ImageToRequestBody(imageFile)); //your imageFile to Request body.
    hashMap.put("user_id",StringToRequestBody("113"));
    //calling addDeal method
    apiInterface.addDeal(hashMap);

希望这对你有所帮助。

我不明白这个!:/ - sreejith v s
你尝试了什么?请求体中有任何问题吗? - Manpreet Singh

0
这对我有用:使用Retrofit 2.0 POST多部分表单数据,包括图像
public interface ApiInterface {

    @Multipart
    @POST("/api/Accounts/editaccount")
    Call<User> editUser (@Header("Authorization") String authorization, @Part("file\"; filename=\"pp.png\" ") RequestBody file , @Part("FirstName") RequestBody fname, @Part("Id") RequestBody id);
    }

    File file = new File(imageUri.getPath());
    RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file);
    RequestBody name = RequestBody.create(MediaType.parse("text/plain"), firstNameField.getText().toString());
    RequestBody id = RequestBody.create(MediaType.parse("text/plain"), AZUtils.getUserId(this));
    Call<User> call = client.editUser(AZUtils.getToken(this), fbody, name, id);

    call.enqueue(new Callback<User>() {
        @Override
        public void onResponse(retrofit.Response<User> response, Retrofit retrofit) {
            AZUtils.printObject(response.body());
        }

        @Override
        public void onFailure(Throwable t) {
            t.printStackTrace();
        }
});

无法使用Retrofit 2.0。请使用1+版本。 - sreejith v s

0

看起来你可以将@Body作为TypedString发送。
例如,将"@Body Deal deal"转换为JSON字符串,并将其作为TypedString发送。

详情请参见:如何使用Retrofit发送multipart/form-data?

@Multipart
@POST("/api/v1/articles/")
Observable<Response> uploadFile(@Part("author") TypedString authorString,
                                @Part("photo") TypedFile photoFile);

谢谢。让我试试这个。 - sreejith v s

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接