我正在使用 retrofit 2 库将图像从 android 设备发送到在 Spring - Boot 上运行的服务器。 我只想发送一张图片看看是否一切正常,所以我执行这种简单类型的请求:
在服务器端我的 Controller 看起来像这样:
@PostMapping(value = "/updatePhoto" )
public String updateUserPhoto(@RequestPart(name = "img") MultipartFile img) {
{
System.out.println("Request update photo "+ img.getOriginalFilename());
return "OK";
}
这是我的要求
@POST("/updatePhoto")
@Multipart
Call<String> updateUserPhoto(@Part MultipartBody.Part img);
我是这样执行的:
File file = new File(mediaPath);
RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
System.err.println(filename+" " + fileToUpload);
MainAplication.getServerRequests().updateUserPhoto(fileToUpload)
.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.body()!=null){
System.err.println(response.body());
}else{
System.err.println("RESPONSE BODY NULL");
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
System.err.println("UPDATE PHOTO FAIL " +t.getMessage());
}
});
但是每次我尝试发送图像时,我的服务器都会抛出异常:
org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'img' is not present
并且无法理解我
哪里做错了,我已经尝试了很多,但无法解决这个问题。有什么我必须改进的想法吗?
最佳答案
试试这个“img”而不是"file"
RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("img", file.getName(), requestBody);
关于java - 从 Android 上传图像到 Spring-Boot Web 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48912853/