如何将图像文件与我的 json 一起上传。
我的请求 JSON 格式如下。
{
"Request": {
"first_name": "Josmy",
"last_name": "J",
"profile_image_attributes": {
"image":"file"
}
}
}
在我的 gson 类中,我正在输入类似这样的值
public class Request implements Serializable {
@SerializedName("first_name")
private String firstName;
@SerializedName("last_name")
private String lastName;
@SerializedName("profile_image_attributes")
private MultipartBody.Part profileImageAttributes;
}
@Headers("Content-Type:application/json")
@POST(PSDApiconstants.REGISTRATION)
Observable<PSDSignUpResponseBean> registration(@Body PSDRegistrationRequestBean requestBean);
有没有办法不把请求改成
{
"imag": "File",
"first_name": "Josmy",
"last_name": "J",
}
编辑
目前我认为retrofit 2.0.1不支持这种模式下的图片上传。所以我使用 Asynchttp 来解决这个问题。但可能是 retrofit 2 将在 7 月底将其包含在他们的最新版本中
最佳答案
在 retrofit 2.0 中,您可以使用 MultipartBody.Part 上传图像。
声明你的服务
@Multipart
@POST("/api/imageupload")
Observable<Response> uploadImage(@Part MultipartBody.Part imageFile);
创建您的改造客户端对象并调用您的 api。
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(YOUR_API_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
//prepare image file
File file = new File(imagePath);
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part imageFileBody = MultipartBody.Part.createFormData("image", file.getName(), requestBody);
YourAPI service = retrofit.create(YourAPI.class);
Call<Response> call = service.uploadImage(imageFileBody);
call.enqueue(new Callback<Response>() {
@Override
public void onResponse(Call<Response> call, Response<Response> response) {
//handle success
}
@Override
public void onFailure(Call<User> call, Throwable t) {
//handle error
}
}
关于android - 如何在 Android 中使用 retrofit 2 以 JSON 格式上传多部分图像数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37785512/