我曾经使用改造1.9 发送 POST 请求:
TypedFile typedFile = picture != null ? new TypedFile("image/*", tempFile) : null;
@Multipart
@POST("/goals")
Observable<Goal> postGoal(
@Part("name") String name,
@Part("picture") TypedFile picture
);
我转向改进2.0.2 ,但我无法使其工作相同。根据我使用的Store and Retrieve Files with Amazon S3:
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), name);
RequestBody picture = RequestBody.create(MediaType.parse("image/*"), tempFile);
@Multipart
@POST("goals")
Observable<Goal> postGoal(
@Part("name") RequestBody name,
@Part("picture\"; filename=\"temp.png\" ") RequestBody picture
);
但似乎请求没有文件(照片)。有什么问题?
答案 0 :(得分:4)
要使用retrofit 2.0上传图像,您可以使用MultipartBody.Part作为图像的参数。希望这个解决方案可以解决您的问题。
您的API声明
@Multipart
@POST("/goals")
Observable<Goal> postGoal(@Part("name") String name, @Part MultipartBody.Part imageFile);
您的api致电
RequestBody imageName = RequestBody.create(MediaType.parse("text/plain"), name);
//prepare image file
File file = new File(imagePath);
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part imageFileBody = MultipartBody.Part.createFormData("picture", file.getName(), requestBody);
YourAPI service = retrofit.create(YourAPI.class);
Call<Goal> call = service.postGoal(imageName, imageFileBody);
call.enqueue(new Callback<Goal>() {
@Override
public void onResponse(Call<Goal> call, Response<Goal> response) {
//handle success
}
@Override
public void onFailure(Call<Goal> call, Throwable t) {
}
});