作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用改进的多部分 api 上传图像。我在 postman 中取得了成功,但在代码中出现以下错误:
Response{protocol=http/1.1, code=422, message=Unprocessable Entity, url=http://upload-snack.13.251.251.232.nip.io/upload}
postman :
改造代码:
请求:
@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;
}
Activity 类代码:
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");
}
});
}
我已经检查了以下教程/答案,但没有任何效果:
还有更多......
但仍然无法正常工作。请帮忙
最佳答案
更改媒体类型 image/* multipart/form-data 实例。我想这会对你有帮助。
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);
关于java - 改造图片上传无法处理实体错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59486478/
我有以下正则表达式 /[a-zA-Z0-9_-]/ 当字符串只包含从 a 到z 大小写、数字、_ 和 -。 我的代码有什么问题? 能否请您向我提供一个简短的解释和有关如何修复它的代码示例? //var
我是一名优秀的程序员,十分优秀!