spring-mvc - 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;
}
解决方案
也许您应该将 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' />",
推荐阅读
- python - 根据项目索引在数组中构建组(Python)
- php - 如何在 woocommecre 上的简单/可下载产品的 zip 文件中显示“包含的文件类型”
- python - Python参数化列表中的所有组合
- javascript - 打字稿不加载与父文件夹同名的文件
- python - nn.Sequential 中的 LayerNorm 在 Torch 中
- hive - 执行 DESC FORMATTED 命令时 Hive 命令提示错误
- python - 在 Pytorch 上使用 sigmoid 输出进行交叉熵损失
- php - 在引导模式中发布详细信息
- bash - 使用带有 awk 的 bash 脚本作为命令
- c# - C# 9.0 记录 ToString()