首页 > 解决方案 > spring mvc中不存在必需的CommonMultipartFile参数'testFile'

问题描述

当我将文件上传到springmvc时,收到错误消息“Required CommonsMultipartFile parameter 'textFile' is not present”,我不知道为什么我能遇到它,这是我的代码。

<form id="form" enctype="multipart/form-data">
<input type="text" id="username" name="username" />
<input type="file" id="file" name="textFile" />
<input type="button" onclick="test()" value="上传" />
</form>

<script type="text/javascript">
function test(){
    var form = new FormData(document.getElementById("form"));
    $.ajax({
        url:"http://localhost:8080/giraffe/upload1",
        type:"post",
        data:form,
        cache: false,
        processData: false,
        contentType: false,
        success:function(data){
            alert("success!");
        }
    });
}

那是我的控制器和配置。

<bean id="multipartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="UTF-8"/>

    <property name="maxUploadSize" value="10240000"/>
</bean>

@RequestMapping(path = "/upload1", method = RequestMethod.POST)
public Object updloadImage(@RequestParam("textFile") CommonsMultipartFile file){
    String fileName = file.getOriginalFilename();

    return null;
}

标签: spring-mvc

解决方案


也许您应该将 RequestParam 更改为

@RequestParam MultipartFile textFile

这是“org.springframework.web.multipart.MultipartFile”类型

同样重要的是您将公共库公开给您的服务器。所以你必须将你的 commons-fileupload-xxxjar 添加到 WEB-INF/lib 文件夹中。

并且您的控制器必须添加路径

@RequestMapping(value="/giraffe")

因为您的 AJAX-Request 指向 /giraffe/upload1

要检查向控制器提供的内容以及是否有任何内容,您可以添加

@RequestParam (required=false) ...

如果您有页面的 jsp 文件并且没有纯 html,那么您可以使用 jstl。这可以帮助您避免 AJAX 请求中的正确 url 出现问题。像这样

url: "<c:url value='/giraffe/upload1' />",

推荐阅读