筆者計劃為大家介紹分布式檔案系統,用于存儲應用的圖檔、word、excel、pdf等檔案。在開始介紹分布式檔案系統之前,為大家介紹一下使用本機存儲來存放檔案資源。 二者的核心實作過程是一樣的:
- 上傳檔案,儲存檔案(本節是本地磁盤)
- 傳回檔案HTTP通路服務路徑給前端,進行上傳之後的效果展示
一、複習
服務端接收上傳的目的是提供檔案的通路服務,那麼對于SpringBoot而言,有哪些可以提供檔案通路的靜态資源目錄呢?
-
,classpath:/META-INF/resources/
-
,classpath:/static/
-
,classpath:/public/
-
classpath:/resources/
這是之前我們為大家介紹的内容,從這裡看出這裡的靜态資源都在classpath下。那麼就出現問題:
- 應用的檔案資源不能和項目代碼分開存儲(你見過往github上傳代碼,還附帶項目檔案資料的麼?)
- 項目打包困難,當上傳的檔案越來越多,項目的打包jar越來越大。
- 代碼與檔案資料不能分開存儲,就意味着檔案資料的備份将變得複雜
二、檔案上傳目錄自定義配置
怎麼解決上述問題?别忘記了spring boot 為我們提供了使用
spring.resources.static-locations
配置自定義靜态檔案的位置。
web:
upload-path: D:/data/
spring:
resources:
static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${web.upload-path}
- 配置
為與項目代碼分離的靜态資源路徑,即:檔案上傳儲存根路徑web.upload-path
- 配置
,除了帶上Spring Boot預設的靜态資源路徑之外,加上file:${web.upload-path}指向外部的檔案資源上傳路徑。該路徑下的靜态資源可以直接對外提供HTTP通路服務。spring.resources.static-locations
三、檔案上傳的Controller實作
詳情看代碼注釋
@RestController
public class FileUploadController {
//綁定檔案上傳路徑到uploadPath
@Value("${web.upload-path}")
private String uploadPath;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
@PostMapping("/upload")
public String upload(MultipartFile uploadFile,
HttpServletRequest request) {
// 在 uploadPath 檔案夾中通過日期對上傳的檔案歸類儲存
// 比如:/2019/06/06/cf13891e-4b95-4000-81eb-b6d70ae44930.png
String format = sdf.format(new Date());
File folder = new File(uploadPath + format);
if (!folder.isDirectory()) {
folder.mkdirs();
}
// 對上傳的檔案重命名,避免檔案重名
String oldName = uploadFile.getOriginalFilename();
String newName = UUID.randomUUID().toString()
+ oldName.substring(oldName.lastIndexOf("."), oldName.length());
try {
// 檔案儲存
uploadFile.transferTo(new File(folder, newName));
// 傳回上傳檔案的通路路徑
String filePath = request.getScheme() + "://" + request.getServerName()
+ ":" + request.getServerPort() + format + newName;
return filePath;
} catch (IOException e) {
throw new CustomException(CustomExceptionType.SYSTEM_ERROR);
}
}
}
四、寫一個模拟的檔案上傳頁面,進行測試
把該upload.html檔案放到classpath:public目錄下,對外提供通路。
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="uploadFile" value="請選擇上傳檔案">
<input type="submit" value="儲存">
</form>
</body>
</html>
通路測試、點選“選擇檔案”,之後儲存

檔案被儲存到服務端的
web.upload-path
指定的資源目錄下
浏覽器端響應結果如下,傳回一個檔案HTTP通路路徑:
使用該HTTP通路路徑,在浏覽器端通路效果如下。證明我們的檔案已經成功上傳到服務端,以後需要通路該圖檔就通過這個HTTP URL就可以了。
歡迎關注我的部落格,裡面有很多精品合集
- 本文轉載注明出處(必須帶連接配接,不能隻轉文字):字母哥部落格。
覺得對您有幫助的話,幫我點贊、分享!您的支援是我不竭的創作動力! 。另外,筆者最近一段時間輸出了如下的精品内容,期待您的關注。
- 《手摸手教你學Spring Boot2.0》
- 《Spring Security-JWT-OAuth2一本通》
- 《實戰前後端分離RBAC權限管理系統》
- 《實戰SpringCloud微服務從青銅到王者》
- 《VUE深入淺出系列》