在 Spring 中,文件上传的工具类是 MultipartFile ,本次的用例也采用该工具类。
使用含文件标签的表单提交
这种方式比较简单,使用用户可见的提交按钮进行文件的上传
前端页面
<form action="/up/u" enctype="multipart/form-data"method="post">
<input type="file" name="oneFile" value="上传文件"/>
<input type="submit" value="单文件上传">
</form>
<hr>
<form action="/up/uM" method="post" enctype="multipart/form-data">
<input type="file" name="file1">
<input type="file" name="file1">
<input type="file" name="file1">
<input type="submit" value="多文件上传">
</form>
<hr>
<form action="/up/uMultiple" method="post" enctype="multipart/form-data">
<input type="file" name="files" multiple>
<input type="submit" value="同一标签多文件上传">
</form>
后台 Controller
@Controller
@RequestMapping("up")
public class UploadContorller {
/**
* 上传文件写入到磁盘
*
* @param multipartFile 写入的文件
* @param path 写入文件的文件夹
*/
private void writeFile(MultipartFile multipartFile, String path) throws IOException {
// 如果没有文件上传,MultipartFile也不会为null,可以通过调用getSize()方法获取文件的大小来判断是否有上传文件
if (multipartFile.getSize() <= 0) {
return;
}
File file = new File(path);
if (!file.exists()) {
file.mkdir();
System.out.println(file.getPath() + "不存在,现已被创建");
}
file = new File(path, multipartFile.getOriginalFilename());
multipartFile.transferTo(file);
}
/**
* 单文件上传
*/
@RequestMapping(value = "u", method = RequestMethod.POST)//文件上传的表单一定要用post
@ResponseBody
// MultipartFile对象跟表单中file类型标签对应,框架会自动用MultipartFile对象来接收上传过来的文件
public String uploadOneFile(MultipartFile oneFile, HttpSession session) throws Exception {
// 得到项目在服务器的真实根路径,如:/home/tomcat/webapp/项目名(getServletContext)/images
String path = session.getServletContext().getRealPath("images");
// 得到文件的原始名称,如:abc.png
String fileName = oneFile.getOriginalFilename();
// 通过文件的原始名称,可以对上传文件类型做限制,如:只能上传jpg和png的图片文件
if (fileName.endsWith("txt")) {
writeFile(oneFile, path);
return "success";
}
return "fail";
}
/**
* 多文件上传
*/
@RequestMapping(value = "uM", method = RequestMethod.POST)
@ResponseBody
public String uploadMultipart(@RequestParam("file1") MultipartFile[] multipartFiles, HttpSession httpSession) throws IOException {
String path = httpSession.getServletContext().getRealPath("images");
for (MultipartFile multipartFile : multipartFiles) {
writeFile(multipartFile, path);
}
return "success";
}
@RequestMapping(value = "uMultiple",method = RequestMethod.POST)
@ResponseBody
public String u(MultipartFile[] files, HttpSession httpSession) throws IOException {
String realPath = httpSession.getServletContext().getRealPath("images");
for (MultipartFile multipartFile : files) {
writeFile(multipartFile, realPath);
}
return "success";
}
}
按钮配合Ajax 上传文件
这种方式是,通过一个文件上传按钮,完成文件选择,选择完成后自动使用 Ajax 异步上传文件。
前端
/* load:为按钮,点击后生成一个隐藏的包含 input file 标签的表单 */
$('#load').after('<form id="fo" method="post" enctype="multipart/form-data"> <input type="file" id="load_xls" name="files" style="display:none" onchange ="uploadFile()">');
$('#load').click(function(){
document.getElementById("load_xls").click();
});
function uploadFile(){
var fileFo=new FormData($("#fo")[0]);
$.ajax({
url: "...",
type: "POST",
data: fileFo,
cache:false,
contentType: false,
processData: false,
success: function (data) {
console.log(data);
},
error:function(data){
console.log(data)
}
});
}
后台接收
@RequestMapping(value = "localFile")
@ResponseBody
public String u(MultipartFile[] files, HttpSession httpSession) throws IOException {
String realPath = httpSession.getServletContext().getRealPath("images");
for (MultipartFile multipartFile : files) {
//do something......
}
return "success";
}
上传文件大小限制
Spring 中默认, maxFileSize 即最大文件大小,被限制为1MB;maxRequestSize 即最大请求大小,被限制为10MB
在 application.properties 中,修改默认文件上传大小:
SpringBoot 1.x
spring.http.multipart.max-request-size=20MB
spring.http.multipart.max-file-size=20MB
SpringBoot 2.x
spring.servlet.multipart.max-request-size=20MB
spring.servlet.multipart.max-file-size=20MB