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

标签 java spring file-upload

我正在尝试使用 spring 上传文件。下面是我的代码,我是如何处理它的 但是如果我尝试使用它,我会得到这个响应:

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

最佳答案

Spring 需要

<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>

关于java - 获取 HTTP 状态 400 - 必需的 MultipartFile 参数 'file' 在 spring 中不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32990908/

相关文章:

java - 遍历所有字节值 -128-127 而无需在 Java 中强制转换

html - 如何替换 html 中上传输入字段按钮中的文本?

angularjs - Angular : $apply already in progress in IE11, 但在 FF 和 Chrome 中没有

java : How garbage collection works for static final String object declared in interface and class

java - Solr 在 id 搜索中不返回文档

java - apache 集合中的 Transformer15

json - 成功调用 URL 后,Spring RESTful Web 服务返回 404

java - jpa删除错误,同时打印更新sql

Spring Boot 相同的代理消息重复到控制台

php - 如何使为调整图像大小而编写的代码适用于各种图像扩展并对其进行优化?