我正在使用Retrofit 1.9上载图片
TypedFile typedFile = new TypedFile("multipart/form-data", new File(ImagePath));
并且工作正常,现在由于响应代码的要求,我不得不使用Retrofit 2,因此我已经像这样answer相应地更改了代码
RequestBody filebody = RequestBody.create(MediaType.parse("image/*"), file);
我将文件正文与其他参数一起传递以发送请求,因此所有其他值均正确发布,但imagefile未正确发布。
对于这两种情况,API或服务器端代码都没有变化,所以我很好奇我是否必须更改服务器端代码,或者在编写android客户端代码时丢失了某些内容。
看看完整代码
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part filebody = MultipartBody.Part.createFormData("product_img", file.getName(), requestFile);
Call<AddProduct> call = service.sendEditProductRequest(name, filebody );
和restinterface就像
@Multipart
@POST(EDIT_PRODUCT)
Call<AddProduct> sendEditProfileRequest (
@Part("name") RequestBody name,
@Part MultipartBody.Part filebody);
答案 0 :(得分:1)
使用以下代码:
public MultipartBody.Part get(@NonNull File file, @NonNull String key) {
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
return MultipartBody.Part.createFormData(key, filename, requestFile);
}
更多:https://square.github.io/okhttp/3.x/okhttp/okhttp3/MultipartBody.Part.html
答案 1 :(得分:0)
您可以使用以下代码转换图像文件并随请求发送。
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
MultipartBody.Part.createFormData("image", file.getName(), requestFile);