在 Spring Boot 項目中實現(xiàn)文件下載功能
(一)需求
在您的 springboot 項目中,可能會存在讓用戶下載文檔的需求,比如讓用戶下載 readme 文檔來更好地了解該項目的概況或使用方法。
所以,您需要為用戶提供可以下載文件的 API ,將用戶希望獲取的文件作為下載資源返回給前端。
(二)代碼
maven 依賴
請您創(chuàng)建好一個 springboot 項目,一定要引入 web 依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
建議引入 thymeleaf 作為前端模板:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
配置 application
在您的 application.yml
中,進行如下屬性配置:
file: doc-dir: doc/
該路徑就是待下載文件存放在服務器上的目錄,為相對路徑,表示與當前項目(jar包)的相對位置。
將屬性與 pojo 類自動綁定
springboot 中的注解 @ConfigurationProperties
可以將 application 中定義的屬性與 pojo 類自動綁定。所以,我們需要定義一個 pojo 類來做 application 中 file.doc-dir=doc/
的配置綁定:
@ConfigurationProperties(prefix = "file") @Data public class FileProperties { private String docDir; }
注解 @ConfigurationProperties(prefix = "file")
在 springboot 應用啟動時將 file 為前綴的屬性與 pojo 類綁定,也就是將 application.yml
中的 file.doc-dir
與 FileProperties 中的字段 docDir 做了綁定。
激活配置屬性
在啟動類或其他配置類(@Configuration注解標記)上加入 @EnableConfigurationProperties 即可讓 ConfigurationProperties 特性生效。
@SpringBootApplication @EnableConfigurationProperties({FileProperties.class}) public class AutoTestApplication { public static void main(String[] args) { SpringApplication.run(AutoTestApplication.class, args); } }
控制層
在控制層我們將以 spring 框架的 ResponseEntity 類作為返回值傳給前端,其中泛型為 spring io 包的 Resource 類,這意味著返回內(nèi)容為 io 流資源;并在返回體頭部添加附件,以便于前端頁面下載文件。
@RestController @RequestMapping("file") public class FileController { private static final Logger logger = LoggerFactory.getLogger(FileController.class); @Autowired private FileService fileService; @GetMapping("download/{fileName}") public ResponseEntity<Resource> downloadFile(@PathVariable String fileName, HttpServletRequest request) { Resource resource = fileService.loadFileAsResource(fileName); String contentType = null; try { contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath()); } catch (IOException e) { logger.error("無法獲取文件類型", e); } if (contentType == null) { contentType = "application/octet-stream"; } return ResponseEntity.ok() .contentType(MediaType.parseMediaType(contentType)) .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"") .body(resource); } }
服務層
服務層的主要工作是把文件作為 IO 資源加載。注意,在 Service 實現(xiàn)類的構(gòu)造方法中要使用 @Autowired 注入前面定義好的屬性綁定類 FileProperties.
@Service public class FileServiceImpl implements FileService { private final Path filePath; @Autowired public FileServiceImpl(FileProperties fileProperties) { filePath = Paths.get(fileProperties.getDocDir()).toAbsolutePath().normalize(); } @Override public Resource loadFileAsResource(String fileName) { Path path = filePath.resolve(fileName).normalize(); try { UrlResource resource = new UrlResource(path.toUri()); if (resource.exists()) { return resource; } throw new FileException("file " + fileName + " not found"); } catch (MalformedURLException e) { throw new FileException("file " + fileName + " not found", e); } } }
自定義異常
在服務層,我們拋出自定義的文件異常 FileException.
public class FileException extends RuntimeException { public FileException(String message) { super(message); } public FileException(String message, Throwable cause) { super(message, cause); } }
前端
在前端 html 頁面,可以使用 a 標簽來下載文件,注意在 a 標簽中定義 download 屬性來規(guī)定這是一個下載文件。
<a href="/file/download/readme.pdf" rel="external nofollow" download>下載使用手冊</a>
(三)參考博客
更多關于 springboot 項目上傳、下載文件的功能請參考:Spring Boot File Upload / Download Rest API Example
總結(jié)
以上所述是小編給大家介紹的在 Spring Boot 項目中實現(xiàn)文件下載功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
相關文章
Java中spring boot 字符串判斷是否為空方法小結(jié)
這篇文章主要介紹了Java中spring boot字符串判斷是否為空,通過安裝依賴,結(jié)合實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2023-11-11基于Javamail實現(xiàn)發(fā)送郵件(QQ/網(wǎng)易郵件服務器)
這篇文章主要介紹了基于Javamail實現(xiàn)發(fā)送郵件,分別使用QQ郵箱作為smtp郵件服務器發(fā)送郵件,使用網(wǎng)易郵箱作為smtp郵件服務器發(fā)送郵件,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-08-08