当前位置: 首页 > 面试题库 >

获取HTTP状态400-Spring中不存在必需的MultipartFile参数'file'

亢雅懿
2023-03-14
问题内容

我正在尝试使用上传文件spring。下面是我的代码如何工作,但是如果我尝试使用它,则会得到以下信息response

HTTP状态400-所需的MultipartFile参数’file’不存在

我不明白错误是什么。

我正在使用高级Rest Client进行测试,并且正在将文件作为附件上传。

我的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.";
        }
    }

问题答案:

春天需要

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

bean处理文件上载。

您应该在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>


 类似资料: