获取HTTP状态码400 - 在Spring中未提供所需的MultipartFile参数“file”

7

我正在尝试使用 spring 上传文件。以下是我的代码:

但是,如果我尝试使用它,我会得到这个 response:

HTTP状态400 - 缺少必需的MultipartFile参数“file”

我不知道错误在哪里。

我正在使用高级REST客户端进行测试,并将文件作为附件上传。

我的Java代码:

@RequestMapping(value = "/upload",headers = "Content-Type=multipart/form-data", method = RequestMethod.POST)
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file)
    {
        String name= "test.xlsx";
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(new File(name)));
                stream.write(bytes);
                stream.close();
                return "You successfully uploaded " + name + "!";
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + name + " because the file was empty.";
        }
    }

1
你能分享一下你的请求吗? - Patrick
你的 context.xml 文件中是否有 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" /> 这段代码? - Patrick
没有它的用途和需要存放的位置。 - Labeo
在调度器Servlet中?在我的情况下 - Labeo
展示你的 JSP,其中你发送了该请求,并展示你声明 bean 的配置。 - We are Borg
显示剩余8条评论
3个回答

7

Spring需要以下bean来处理文件上传:

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

你应该在application context文件中注册这个bean

同时,Content-Type也应该是有效的。在你的情况下,使用enctype="multipart/form-data"

编辑1:

你可以为bean属性设置上传和内存大小:

  <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- max upload size in bytes -->
        <property name="maxUploadSize" value="20971520" /> <!-- 20MB -->

        <!-- max size of file in memory (in bytes) -->
        <property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->

    </bean>

我能否将内容类型更改为其他类型? - Labeo
这取决于您或客户想要发送的内容类型以及服务器接收的内容类型。我认为它也应该能够使用application/json - Patrick
上传文件的最大大小是多少? - Labeo
我们不需要在'web.xml'文件中声明Multipart过滤器吗?像这样:<filter>     <filter-name>multipartResolver</filter-name>     <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>   </filter>   <filter-mapping>     <filter-name>multipartResolver</filter-name>     <url-pattern>/*</url-pattern>   </filter-mapping> - Shamim Ahmad
起初似乎无法工作,但当我重新启动服务器后它就可以了。谢谢 :) - ZAIRI Oussama
这是配置Java bean的方法 - https://dev59.com/s18e5IYBdhLWcg3wEXFi - Xdg

2
当您在高级 REST 客户端中预先选择文件时,在右侧会有一个输入框,请在该输入框中编写参数名称,对于您的情况,参数名称为“file”。
控制器中定义参数名称为“@RequestParam("file")”。

enter image description here


是的,我正在那种方式下使用。 - Labeo
please attach your screenshot - Sanjay Singh Rawat
你有用于此情况的任何bean id吗?如果我使用bean id,它在我的情况下解决了问题。 - Labeo

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接