SpringBoot - 實現檔案上傳1(單檔案上傳、常用上傳引數配置)
阿新 • • 發佈:2021-12-14
Spring Boot對檔案上傳做了簡化,基本做到了零配置,我們只需要在專案中新增spring-boot-starter-web依賴即可。
一、單檔案上傳
1,程式碼編寫
(1)首先在static目錄中建立一個upload.html檔案,內容如下:<!DOCTYPE html> <html lang="en"> <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>
(2)接著建立檔案上傳處理介面FileUploadController.java,內容如下:
import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat;import java.util.Date; import java.util.UUID; @RestController public class FileUploadController { SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/"); @PostMapping("/upload") public String upload(MultipartFile uploadFile, HttpServletRequest req) { // 上傳的檔案將儲存在專案執行目錄下的 uploadFile 資料夾, String realPath = req.getSession().getServletContext().getRealPath("/uploadFile/"); System.out.println(realPath); // 並且在 uploadFile 資料夾中通過日期對上傳的檔案歸類儲存 String format = sdf.format(new Date()); File folder = new File(realPath + 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 = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/uploadFile/" + format + newName; return filePath; } catch (IOException e) { e.printStackTrace(); } return "上傳失敗!"; } }
2,執行測試
(1)我們使用瀏覽器訪問upload.html頁面並選擇檔案上傳:
(2)上傳成功後會返回上傳檔案的訪問路徑:(3)使用這個訪問路徑我們就可以看到剛剛上傳的檔案:
附:常用引數配置
(1)如果我們需要對圖片上傳的細節進行配置,也是可以的。比如我們可以在application.properties檔案中新增如下配置:spring.servlet.multipart.enabled=true
spring.servlet.multipart.file-size-threshold=0
spring.servlet.multipart.location=D:\\workspace
spring.servlet.multipart.max-file-size=1MB
spring.servlet.multipart.max-request-size=10MB
spring.servlet.multipart.resolve-lazily=false
yml版本
spring:
servlet:
multipart:
enabled:true
file-size-threshold:''
location:D:\\workspace
max-file-size:1MB
max-request-size:10MB
resolve-lazily:false
(2)上面幾個引數作用如下:
- spring.servlet.multipart.enabled:表示是否開啟檔案上傳支援,預設為true
- spring.servlet.multipart.file-size-threshold:表示檔案寫入磁碟的閥值,預設為0
- spring.servlet.multipart.location:表示上傳檔案的臨時儲存位置
- spring.servlet.multipart.max-file-size:表示上傳的單個檔案的最大大小,預設為1MB
- spring.servlet.multipart.max-request-size:表示多檔案上傳時檔案的總大小,預設為10MB
- spring.servlet.multipart.resolve-lazily:表示檔案是否延遲解析,預設為false