更新时间:2023-01-03 16:44:11
我前几天遇到了类似的问题。这里说到我的工作code。
I faced a similar problem a few days ago. Here comes my working code.
首先,你必须定义接口。不添加的内容类型头是非常重要的。
在下面可以看到 @part(图片\\;
图片是对应的名称,后端预期(对我来说),所以你不得不这样做。更改此名称,使其与您的后端工作。文件名= \\图片\\只是定义了你上传的图片的名称。
在我的情况的方法是在DiaryService.java。
At first you have to define the Interface. It is very important NOT to add a content type header.
In the following you see the @Part("picture\";
the "picture" is the corresponding name, that the Backend expects (in my case). So you have to change this name to make it work with your Backend. The filename=\"image\" just defines the name of your uploaded image.
In my case the method is in the "DiaryService.java".
@Multipart
@POST("signature/upload")
public Call<Void> addImageElementToDiary(@Part("picture\"; filename=\"image\" ") RequestBody picture,
@Part("sort") RequestBody sort);
现在您可以拨打上述定义的服务。重要的是要正确分析的MediaType是非常重要的。你用的multipart / form-data的,这并没有我的情况下工作。您应该在以下Mediatypes看看。
Now you can call the above defined Service. It is important to parse the Mediatype correctly. You used "multipart/form-data", this did not work in my case. You should take a look at the following Mediatypes.
File file = new File(((CreateDiaryImage) element).getImagePath());
RequestBody sort = RequestBody.create(MediaType.parse("text/plain"), element.getSort() + "");
RequestBody requestBody =
RequestBody.create(MediaType.parse("image/*"), file);
Call<Void> call = diaryService.addImageElementToDiary(requestBody, sort);
call.enqueue(new Callback<Void>() {
@Override
public void onResponse(Response<Void> response, Retrofit retrofit) {
Log.v("Upload", "success");
}
@Override
public void onFailure(Throwable t) {
Log.e("Upload", t.getMessage());
}
});