【发布时间】:2020-04-16 13:57:26
【问题描述】:
我正在使用改造多部分 API 上传图像。我在邮递员中取得了成功,但在代码中得到了以下错误:
响应{protocol=http/1.1, code=422, message=Unprocessable Entity, url=http://upload-snack.13.251.251.232.nip.io/upload}
邮递员:
改造代码:
请求:
@Multipart
@POST("upload")
Call<ResponseBody> uploadImage(@Part MultipartBody.Part image);
界面:
public static Retrofit getRetrofitClient(Context context, String baseURL) {
if (retrofit == null) {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.build();
retrofit = new Retrofit.Builder()
.baseUrl(baseURL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
活动类代码:
private void uploadToServer(String filePath) {
Retrofit retrofit = ServiceGenerator.getRetrofitClient(this, "http://upload-snack.13.251.251.232.nip.io/");
Api uploadAPIs = retrofit.create(Api.class);
//Create a file object using file path
File file = new File(filePath);
// Create a request body with file and image media type
RequestBody fileReqBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
// Create MultipartBody.Part using file request-body,file name and part name
MultipartBody.Part part = MultipartBody.Part.createFormData("image", file.getName(), fileReqBody);
//Create request body with text description and text media type
// RequestBody description = RequestBody.create(MediaType.parse("text/plain"), "image-type");
//
Call call = uploadAPIs.uploadImage(part);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
Log.e("response", response.toString());
}
@Override
public void onFailure(Call call, Throwable t) {
Log.e("failure", "failure");
}
});
}
我检查了下面的教程/答案,但没有任何效果:
- https://android.jlelse.eu/working-with-retrofit-825d30348fe2
- https://inducesmile.com/android/android-upload-image-to-server-using-retrofit-2/
- image upload using multipart retrofit 2
- Upload image into server using retrofit
- https://www.simplifiedcoding.net/retrofit-upload-file-tutorial/
- https://www.journaldev.com/23738/android-multipart-image-upload-progress-retrofit-nodejs
- Image upload using retrofit
- How to Upload Image file in Retrofit 2
- Retrofit 2 Multipart image upload with data
- POST Multipart Form Data using Retrofit 2.0 including image
- Retrofit Uploading multiple images to a single key
还有更多.....
但仍然无法正常工作。请帮忙
【问题讨论】:
-
我也遇到了同样的问题,请问您找到解决方法了吗?如果有任何解决方案,请告诉我。
-
@Akshay 需要将媒体类型更改为 image/png 而不是 multipart/form-data。那会奏效的。
-
@VishvaDave 非常感谢,它现在正在工作。
标签: java android retrofit retrofit2