本文來自于千鋒教育在阿裡雲開發者社群學習中心上線課程《SpringBoot實戰教程》,主講人楊紅豔,
點選檢視視訊内容。
SpringBoot實作檔案上傳
在工程中添加依賴:
<!-- spring boot web支援 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- thymeleaf模闆依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
控制上傳檔案的大小,在全局配置檔案application.properties中添加:
multipart.maxFileSize=500Mb
multipart.maxRequestSize=500Mb
實作上傳的頁面:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"></meta>
<title>檔案上傳</title>
</head>
<body>
<h2>檔案上傳</h2>
<hr/>
<form method = "POST" enctype="multipart/form-data" action="/upload">
<p>
檔案<input type="file" name="file"/>
</p>
<p>
<input type="submit" value="上傳"/>
</p>
</form>
</body>
</html>
UploadController:
@Controller
public class UploadController {
@RequestMapping("/index")
public String toUpload(){
return "upload";
}
@RequestMapping(value="/upload",method=RequestMethod.POST)
@ResponseBody
public String uploadFile(MultipartFile file, HttpServletRequest request) {
try{
//建立檔案在伺服器端的存放路徑
String dir=request.getServletContext().getRealPath("/upload");
File fileDir = new File(dir);
if(!fileDir.exists())
fileDir.mkdirs();
//生成檔案在伺服器端存放的名字
String fileSuffix=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
String fileName=UUID.randomUUID().toString()+fileSuffix;
File files = new File(fileDir+"/"+fileName);
//上傳
file.transferTO(files);
}catch(Exception e) {
e.printStackTrace();
return "上傳失敗";
}
return "上傳成功";
}
}
在啟動類中添加所有需要掃描的包:
@SpringBootApplication(scanBasePackages="com.qianfeng")
執行結果:
選擇檔案上傳