在SpringBoot中驗證使用者上傳的圖片資源
阿新 • • 發佈:2020-07-15
允許使用者上傳圖片資源(頭像,發帖)是APP常見的需求,特別需要把使用者的資源IO到磁碟情況下,需要防止壞人提交一些非法的檔案,例如木馬,webshell,可執行程式等等。這類非法檔案不僅會導致客戶端圖片資源顯示失敗,而且還會給伺服器帶來安全問題。
通過檔案字尾判斷檔案的合法性
這種方式比較常見,也很簡單,是目前大多數APP選擇的做法。
public Object upload (@RequestParam("file") MultipartFile multipartFile) throws IllegalStateException, IOException { // 原始檔名稱 String fileName = multipartFile.getOriginalFilename(); // 解析到檔案字尾,判斷是否合法 int index = fileName.lastIndexOf("."); String suffix = null; if (index == -1 || (suffix = fileName.substring(index + 1)).isEmpty()) { return "檔案字尾不能為空"; } // 允許上傳的檔案字尾列表 Set<String> allowSuffix = new HashSet<>(Arrays.asList("jpg", "jpeg", "png", "gif")); if (!allowSuffix.contains(suffix.toLowerCase())) { return "非法的檔案,不允許的檔案型別:" + suffix; } // 序列化到磁碟中的檔案上傳目錄, /upload // FileCopyUtils.copy 方法會自動關閉流資源 FileCopyUtils.copy(multipartFile.getInputStream(), Files.newOutputStream(Paths.get("D://upload", fileName), StandardOpenOption.CREATE_NEW)); // 返回相對訪問路徑,檔名極有可能帶中文或者空格等字元,進行uri編碼 return "/" + UriUtils.encode(fileName, StandardCharsets.UTF_8); }
使用 ImageIO 判斷是否是圖片
這個方法就比較嚴格了,在判斷後綴的基礎上,使用Java的ImageIO
類去載入圖片,嘗試讀取其寬高資訊,如果不是合法的圖片資源。則無法讀取到這兩個資料。就算是把非法檔案修改了字尾,也可以檢測出來。
public Object upload (@RequestParam("file") MultipartFile multipartFile) throws IllegalStateException, IOException { // 原始檔名稱 String fileName = multipartFile.getOriginalFilename(); // 解析到檔案字尾 int index = fileName.lastIndexOf("."); String suffix = null; if (index == -1 || (suffix = fileName.substring(index + 1)).isEmpty()) { return "檔案字尾不能為空"; } // 允許上傳的檔案字尾列表 Set<String> allowSuffix = new HashSet<>(Arrays.asList("jpg", "jpeg", "png", "gif")); if (!allowSuffix.contains(suffix.toLowerCase())) { return "非法的檔案,不允許的檔案型別:" + suffix; } // 臨時檔案 File tempFile = new File(System.getProperty("java.io.tmpdir"), fileName); try { // 先把檔案序列化到臨時目錄 multipartFile.transferTo(tempFile); try { // 嘗試IO檔案,判斷檔案的合法性 BufferedImage bufferedImage = ImageIO.read(tempFile); bufferedImage.getWidth(); bufferedImage.getHeight(); } catch (Exception e) { // IO異常,不是合法的圖片檔案,返回異常資訊 return "檔案不是圖片檔案"; } // 複製到到上傳目錄 FileCopyUtils.copy(new FileInputStream(tempFile), Files.newOutputStream(Paths.get("D://upload", fileName), StandardOpenOption.CREATE_NEW)); // 返回相對訪問路徑 return "/" + UriUtils.encode(fileName, StandardCharsets.UTF_8); } finally { // 響應客戶端後,始終刪除臨時檔案 tempFile.delete(); } }
總結
使用ImageIo
的方式更為保險,但是需要多幾次IO操作。比較消耗效能。而且今天APP大都是用雲端儲存服務,類似於阿里雲的OSS。直接就把客戶端上傳的檔案PUT到了雲端,才不管使用者上傳的圖片是不是真正的圖片,非法上傳,最多導致客戶端不能顯示而已,但是威脅不了伺服器的安全。