在 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