【问题标题】:Uploading image to a Spring-Boot web server from android从 android 将图像上传到 Spring-Boot Web 服务器
【发布时间】:2018-02-21 18:17:40
【问题描述】:

我正在使用改造 2 库将图像从 android 设备发送到在 Spring - Boot 上运行的服务器。 我想简单地发送一张图片看看,如果一切正常,所以我执行这种简单类型的请求:

在服务器端,我的控制器如下所示:

 @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

cant understand where im 做错了,我尝试了很多,但无法解决这个问题。有什么想法我必须改进吗?

【问题讨论】:

    标签: java android spring-mvc retrofit2 multipartform-data


    【解决方案1】:

    试试这个“img”而不是“file”

     RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
     MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("img", file.getName(), requestBody);
    

    【讨论】:

    • 是的,它成功了!)非常感谢)你能用两个词解释一下问题是什么,以及为什么使用“img”而不是“file”来修复它
    • 问题似乎已经接受了一些答案,还是没有解决,是什么问题?
    猜你喜欢
    • 1970-01-01
    • 2017-09-18
    • 2011-02-02
    • 2015-03-29
    • 2011-10-15
    • 2020-11-19
    • 1970-01-01
    相关资源
    最近更新 更多