SpringBoot 檔案上傳+攔截器
檔案上傳原理
- 表單的enctype屬性規定在發送到服務器之前應該如何對表單資料進行編碼,
- 當表單的enctype="application/x-www-form-urlencoded"(默認)時,form表單中的資料格式為:key=value&key=value,
- 當表單的enctype="multipart/form-data"時,其傳輸資料如下:

SpringBoot實作檔案上傳功能
- SpringBoot工程嵌入的tomcat限制了請求的檔案大小,每個檔案的配置最大為1MB,單次請求的檔案總數不能大于10MB,
- 要更改這個默認值需要在組態檔(如application.properties)中加入兩個配置
# 單個檔案大小
spring.servlet.multipart.max-file-size=10MB
# 每次請求所有檔案大小
spring.servlet.multipart.max-request-size=10MB
- 當表單的enctype="multipart/form-data"時,可以使用MultipartFile獲取上傳的檔案資料,再通過transferTo方法將其寫入到磁盤中,
@RestController
public class FileUploadController {
@PostMapping("/upload")
public String up(String nickname, MultipartFile photo, HttpServletRequest request) throws IOException{
System.out.println(nickname);
//獲取圖片的原始名稱
System.out.println(photo.getOriginalFilename());
//獲取檔案型別
System.out.println(photo.getContentType());
String path = request.getServletContext().getRealPath("/upload/");
System.out.println(path);
saveFile(photo,path);
return "上傳成功";
}
public void saveFile(MultipartFile photo, String path) throws IOException {
// 判斷存盤的目錄是否存在,如果不存在則創建
File dir = new File(path);
if (!dir.exists()){
//創建目錄
dir.mkdir();
}
File file = new File(path+photo.getOriginalFilename());
photo.transferTo(file);
}
}
修改瀏覽器訪問此圖片的路徑為:
# 第一個斜線代表服務器所在的目錄
spring.web.resources.static-locations=/upload/
攔截器
- 攔截器在Web系統中非常常見,對于某些全域統一的操作,我們可以把它提取到攔截器中實作,總結起來,攔截器大致有以下使用場景:
- 權限檢查:如登錄檢測,進入處理程式檢測是否登錄,如果沒有,則直接回傳登錄頁面,
- 性能監控:有時系統在某段時間莫名其妙很慢,可以通過攔截器在進入處理程式之前記錄開始時間,在處理完后記錄結束時間,從而得到改請求的處理時間,
- 通用行為:讀取Cookie得到用戶資訊并將用戶物件放入請求,從而方便后續流程使用,還有提取Locale、Theme資訊等,只要是多個處理程式都需要的,即可使用攔截器使用,
-
SpringBoot定義了HandlerInterceptor介面來實作自定義攔截器的功能,
-
HandlerInterceptor介面定義了preHandle、postHandle、afterCompletion三種方法,通過重寫這三種方法實作請求前、請求后等操作,
-
下面定義一個攔截器(注意:定義之后還要注冊,此攔截器才能生效),實作HandlerInterceptor介面并重寫父類方法
public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("LoginInterceptor"); return true; } }
攔截器注冊
- addPathPatterns方法定義攔截的地址
- excludePathPatterns定義排除某些地址不被攔截
- 添加的一個攔截器沒有addPathPattern任何一個url則默認攔截所有請求
- 如果沒有excludePathPatterns任何一個請求,則默認不放過任何一個請求
@Configuration //加上該注解后SpringBoot會自動讀取這個類,這樣下面的配置才能生效
public class WebConfig implements WebMvcConfigurer {
@Override //重寫父類的增加攔截器的方法
public void addInterceptors(InterceptorRegistry registry) {
//把定義的攔截器new出來
//registry.addInterceptor(new LoginInterceptor());
// 只攔截/user/**路徑
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/postTest1");
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/546437.html
標籤:其他
下一篇:python可變長引數
