1、前端页面的样子
2、前端的js代码
var formData = new FormData();
var files = $("#file")[0].files;
for(var i = 0 ; i < files.length ; i ++){
formData.append('file',files[i]);
}3、ajax的代码
$.ajax({
url: '${cpath}/biz/xxxx/addFile',
type: 'POST',
cache: false,
data: formData,
processData: false,
contentType: false
}).done(function(res) {
debugger;
});
4、后端的代码
@RequestMapping(value = "addFile", method = RequestMethod.POST, produces = "application/json; charset=UTF-8")
@ResponseBody
public String addFile(HttpServletRequest request,HttpServletResponse response) {
String rRoles = request.getParameter("rRoles");
List fileList = new ArrayList<>();
//创建一个通用的多部分解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//判断 request 是否有文件上传,即多部分请求
if(multipartResolver.isMultipart(request)){
//转换成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
//取得request中的所有文件名
fileList = multiRequest.getFiles("file");
if (fileList == null || fileList.size() <= 0) {
throw new Exception("上传文件失败");
}
System.out.println("");
}
return null;
}5、xml配置文件配置
>
104857600
4096
6、jar包,除了springmvc常规的jar,还需要commons-fileupload-1.2.2.jar*注意:关于formdata
The append() method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.
The difference between FormData.set and append() is that if the specified key already exists, FormData.set will overwrite all existing values with the new one, whereas append() will append the new value onto the end of the existing set of values.
这篇博客详细介绍了前端使用FormData对象结合Ajax进行文件上传,以及后端使用Spring MVC接收并处理文件的完整流程。包括前端页面的文件选择、js代码中formData的构建、ajax请求设置、后端控制器的@RequestMapping注解处理和多部分请求解析。同时,配置文件中设置了上传文件大小限制,并提及了需要的额外jar包。这是一个完整的前端到后端文件上传实践案例。
1954

被折叠的 条评论
为什么被折叠?



