java - 从 Android 上传图像到 Spring-Boot Web 服务器

标签 java android spring-mvc retrofit2 multipartform-data

我正在使用 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/

相关文章:

java - DFS over string trie (前缀)

android - 如何将设置 Activity 合并到主要 Activity ?

java - 实体未在 Hibernate 中更新

java - 使用 Java 8 流获取 List<String> 和 HashMap<String, Object>

java - Log4j 配置打印到控制台和文件

android phonegap相机和图像上传

android - 如果我有许多具有不同 Url 的按钮,如何在 webview 中设置 Url?

java - 使用 Spring Boot 和安全性进行集成测试

java - 运行 Maven 项目的警告 (Spring MVC)

java - 使用 GSON 自定义枚举反序列化