SpringBoot基礎實戰系列(三)springboot單文件與多文件上傳
- 2020 年 5 月 15 日
- 筆記
- springboot, springboot基礎實戰系列, 文件上傳
springboot單文件上傳
對於springboot文件上傳需要了解一個類MultipartFile
,該類用於文件上傳。我此次使用thymeleaf
模板引擎,該模板引擎文件後綴 .html
。
1.創建controller
/**
* 單文件上傳,使用post請求
* @param file
* @return
*/
@PostMapping("/upload")
@ResponseBody
public String fileupload(MultipartFile file){
// 獲取文件的原文件名
String oldName = file.getOriginalFilename();
// 文件上傳,保存為新的文件名
if (!"".equals(oldName) && oldName != null){
// 獲取文件後綴
String suffixFileName = oldName.substring(oldName.lastIndexOf("."));
// 設置文件保存的文件夾
SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd");
String filePath = "C:/Users/Desktop/springboot" + sdf.format(new Date()) + "/" + UUID.randomUUID() + suffixFileName;
File dest = new File(filePath);
// 判斷文件夾是否存在
if (!dest.exists()){
dest.mkdirs();
}
try {
// 文件寫入
file.transferTo(dest);
// 返迴文件保存成功之後的文件名路徑
return filePath;
} catch (Exception e) {
e.printStackTrace();
}
}
return "文件上傳失敗";
}
2.創建upload.html
頁面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>單文件上傳</div>
<form method="post" enctype="multipart/form-data" action="/upload">
<input name="file" type="file" />
<input type="submit" value="提交" />
</form>
</body>
</html>
注意:
- 對於文件上傳,我們一般使用
post
方法 - 前端
html
頁面我暫時放在static
文件夾下,由於瀏覽器頁面是直接先訪問到html
頁面的,而不是通過controller
跳轉得到的,所以該頁面屬於靜態頁面,而static
文件夾下的資源文件屬於靜態資源文件都是可以直接訪問的。這一點要區別於templates
文件夾。 - 可能出現的報錯:
template might not exist or might not be accessible by any of the configured Template Resolvers
,可能原因是:需要在controller
方法體上加上註解@ResponseBody或@RestController
。
springboot多文件上傳
多文件上傳相比較於單文件上傳,區別於單文件上傳,多文件上傳後端方法使用數組來接收 MultipartFile[] files
,且多文件上傳只是循環調用單文件上傳的方法。
1.創建controller
/**
* 多文件上傳(只是比單文件上傳多了一個循環)
* @param files 文件集合
* @return
*/
@PostMapping("/uploads")
@ResponseBody
public String fileUploadMultipart(MultipartFile[] files, HttpServletRequest request){
// HttpSession session = request.getSession();
// System.out.println(session);
// ServletContext servletContext = session.getServletContext();
// System.out.println(servletContext);
// String context = servletContext.getRealPath("context");
// System.out.println(context);
List<String> list = new ArrayList<String>();
// 此處循環調用單文件的上傳方法
for (int i = 0; i< files.length; i++){
String url = fileupload(files[i]);
list.add(url);
}
return list.toString();
}
2.創建upload.html
頁面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>多文件上傳</div>
<form method="post" enctype="multipart/form-data" action="/uploads">
<input name="files" type="file" multiple/>
<input type="submit" value="上傳"/>
</form>
</body>
</html>
希望自己能一直保持初衷,文章一直寫下去,和大家一起成長
本系列程式碼github地址://github.com/shanggushenlong/springboot-demo