SpringBoot實現(xiàn)文件上傳功能
經(jīng)典的文件上傳
服務(wù)器處理上傳文件一般都是先在請求中讀取文件信息,然后改變名稱保存在服務(wù)器的臨時路徑下,最后保存到服務(wù)器磁盤中。本次以thymeleaf搭建demo,因此需要引入thymeleaf依賴庫。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> <version>2.5.5</version> </dependency>
如果使用的是gradle構(gòu)建的項目,需要修改build.gradle文件:
compile 'org.springframework.boot:spring-boot-starter-thymeleaf:2.5.5'
新建一個Action類負責處理上傳的文件:
@RestController @RequestMapping("/upload/*") public class UploadAction { @PostMapping("/file") public Object uploadHandler(HttpServletRequest request, String title, MultipartFile file) { Map<String, Object> resultMap = new LinkedHashMap<>(); resultMap.put("title", title); resultMap.put("fileName", file.getName()); // 文件名 resultMap.put("originalFilename", file.getOriginalFilename()); // 原始名稱 resultMap.put("content-type", file.getContentType()); // 文件類型 resultMap.put("fileSize", file.getSize() / 1024 + "K"); // 文件大小 try { // 保存文件 String uploadedFilePath = saveFile(request, file.getInputStream(), file.getOriginalFilename() .substring(file.getOriginalFilename().lastIndexOf(".") + 1)); resultMap.put("uploadedFilePath", uploadedFilePath); // 文件大小 } catch (IOException e) { System.err.println("error-path: /upload/file, message: " + e.getMessage()); } return resultMap; } /** * 保存上傳的文件到本地服務(wù)器 * * @param request HttpServletRequest * @param input 輸入流 * @param ext 文件擴展名 * @return 文件路徑 * @throws IOException */ public String saveFile(HttpServletRequest request, InputStream input, String ext) throws IOException { String realPath = request.getServletContext().getRealPath("/upload/file/"); // 取得服務(wù)器真實路徑 File file = new File(realPath); if (!file.getParentFile().exists()) { // 目錄不存在 file.mkdirs(); // 創(chuàng)建多級目錄 } String filePath = realPath + UUID.randomUUID() + "." + ext; // 取的文件輸出流 OutputStream out = new FileOutputStream(filePath); byte[] data = new byte[2048]; // 緩沖數(shù)組2KB int len = 0; // 讀取字節(jié)長度 while ((len = input.read(data)) != -1) { out.write(data, 0, len); // 文件寫入磁盤 } if (input != null) { input.close(); } out.close(); return filePath; } }
在resources目錄下新建templates文件夾,在里面創(chuàng)建index.html文件作為項目首頁展示。
<!doctype HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>文件上傳測試</title> <meta charset="UTF-8" /> </head> <body> <form action="/upload/file" method="post" enctype="multipart/form-data"> <span>標題:</span> <input type="text" name="title" /><br> <span>文件:</span> <input type="file" name="file" /><br> <input type="submit" value="上傳" /> </form> </body> </html>
啟動項目,直接訪問:http://localhost:8080/將進入index.html頁面。
點擊上傳按鈕,文件將被保存到服務(wù)器磁盤中:
SpringBoot對上傳文件處理的簡化
SpringBoot對FileUpload組件進行了整合,在文件保存的時候可以避免直接操作IO流,通過配置文件的方式指定文件上傳的限制參數(shù)。修改application.yml文件:
server: port: 8080 spring: servlet: multipart: enabled: true # 啟用文件上傳 max-file-size: 1MB # 單文件上傳最大限制 max-request-size: 10MB # 文件上傳最大值 file-size-threshold: 10KB # 上傳文件達到多大時寫入磁盤 location: / # 臨時文件存儲位置
修改UploadAction,使用MultipartFile類的transferTo方法保存上傳文件。
@RestController @RequestMapping("/upload/*") public class UploadAction { @PostMapping("/file") public Object uploadHandler(HttpServletRequest request, String title, MultipartFile file) { Map<String, Object> resultMap = new LinkedHashMap<>(); resultMap.put("title", title); resultMap.put("fileName", file.getName()); // 文件名 resultMap.put("originalFilename", file.getOriginalFilename()); // 原始名稱 resultMap.put("content-type", file.getContentType()); // 文件類型 resultMap.put("fileSize", file.getSize() / 1024 + "K"); // 文件大小 try { // 保存文件 String etc = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1); String serverPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/file/upload/"; String fileName = UUID.randomUUID() + "." + etc; resultMap.put("filePath", serverPath + fileName); // 文件地址(服務(wù)器訪問地址) // 文件保存再真實路徑下 File saveFile = new File(request.getServletContext().getRealPath("/file/upload/") + fileName); if (!saveFile.getParentFile().exists()) { // 目錄不存在,創(chuàng)建目錄 saveFile.mkdirs(); } file.transferTo(saveFile); // 保存上傳文件 } catch (IOException e) { System.err.println("error-path: /upload/file, message: " + e.getMessage()); } return resultMap; } }
訪問:http://localhost:8080/
點擊上傳按鈕:
在瀏覽器上訪問filePath,可以預(yù)覽上傳的文件:
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Mybatis或Mybatis-Plus框架的xml文件中特殊符號的使用詳解
這篇文章主要介紹了Mybatis或Mybatis-Plus框架的xml文件中特殊符號的使用詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-11-11通過Feign進行調(diào)用@FeignClient?找不到的解決方案
這篇文章主要介紹了通過Feign進行調(diào)用@FeignClient?找不到的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-0325行Java代碼將普通圖片轉(zhuǎn)換為字符畫圖片和文本的實現(xiàn)
這篇文章主要介紹了25行Java代碼將普通圖片轉(zhuǎn)換為字符畫圖片和文本的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-04-04SpringBoot實現(xiàn)動態(tài)控制定時任務(wù)支持多參數(shù)功能
這篇文章主要介紹了SpringBoot實現(xiàn)動態(tài)控制定時任務(wù)-支持多參數(shù)功能,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-05-05