@Multipart
@POST("/api/add-deal/")
public void addDeal(@Body Deal deal, @Part("image")TypedFile image,Callback<Response> callback);
我想将只有图像作为multipart发送,其余内容保持不变。是否有可能?即使我尝试在我的Deal模型中添加TypedFile,但无法注释@part。
是的,可以使用哈希映射和Partmap注释来实现。例如:
@Multipart
@POST("/api/add-deal/")
Call<Response> addDeal(@PartMap
HashMap<String, RequestBody> hashMap);
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);
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();
}
});
看起来你可以将@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);