在 Spring Boot 項(xiàng)目中實(shí)現(xiàn)文件下載功能
(一)需求
在您的 springboot 項(xiàng)目中,可能會(huì)存在讓用戶下載文檔的需求,比如讓用戶下載 readme 文檔來(lái)更好地了解該項(xiàng)目的概況或使用方法。
所以,您需要為用戶提供可以下載文件的 API ,將用戶希望獲取的文件作為下載資源返回給前端。
(二)代碼
maven 依賴
請(qǐng)您創(chuàng)建好一個(gè) springboot 項(xiàng)目,一定要引入 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
中,進(jìn)行如下屬性配置:
file: doc-dir: doc/
該路徑就是待下載文件存放在服務(wù)器上的目錄,為相對(duì)路徑,表示與當(dāng)前項(xiàng)目(jar包)的相對(duì)位置。
將屬性與 pojo 類自動(dòng)綁定
springboot 中的注解 @ConfigurationProperties
可以將 application 中定義的屬性與 pojo 類自動(dòng)綁定。所以,我們需要定義一個(gè) pojo 類來(lái)做 application 中 file.doc-dir=doc/
的配置綁定:
@ConfigurationProperties(prefix = "file") @Data public class FileProperties { private String docDir; }
注解 @ConfigurationProperties(prefix = "file")
在 springboot 應(yīng)用啟動(dòng)時(shí)將 file 為前綴的屬性與 pojo 類綁定,也就是將 application.yml
中的 file.doc-dir
與 FileProperties 中的字段 docDir 做了綁定。
激活配置屬性
在啟動(dòng)類或其他配置類(@Configuration注解標(biāo)記)上加入 @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 流資源;并在返回體頭部添加附件,以便于前端頁(yè)面下載文件。
@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("無(wú)法獲取文件類型", 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); } }
服務(wù)層
服務(wù)層的主要工作是把文件作為 IO 資源加載。注意,在 Service 實(shí)現(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); } } }
自定義異常
在服務(wù)層,我們拋出自定義的文件異常 FileException.
public class FileException extends RuntimeException { public FileException(String message) { super(message); } public FileException(String message, Throwable cause) { super(message, cause); } }
前端
在前端 html 頁(yè)面,可以使用 a 標(biāo)簽來(lái)下載文件,注意在 a 標(biāo)簽中定義 download 屬性來(lái)規(guī)定這是一個(gè)下載文件。
<a href="/file/download/readme.pdf" rel="external nofollow" download>下載使用手冊(cè)</a>
(三)參考博客
更多關(guān)于 springboot 項(xiàng)目上傳、下載文件的功能請(qǐng)參考:Spring Boot File Upload / Download Rest API Example
總結(jié)
以上所述是小編給大家介紹的在 Spring Boot 項(xiàng)目中實(shí)現(xiàn)文件下載功能,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
- SpringBoot+ruoyi框架文件上傳和下載的實(shí)現(xiàn)
- SpringBoot中的文件上傳和異常處理詳解
- SpringBoot實(shí)現(xiàn)文件上傳下載實(shí)時(shí)進(jìn)度條功能(附源碼)
- SpringBoot簡(jiǎn)單實(shí)現(xiàn)文件上傳
- SpringBoot實(shí)現(xiàn)文件下載功能的方式分享
- vue+element+springboot實(shí)現(xiàn)文件下載進(jìn)度條展現(xiàn)功能示例
- springboot中Excel文件下載踩坑大全
- springboot單文件下載和多文件壓縮zip下載的實(shí)現(xiàn)
- Spring Boot中進(jìn)行 文件上傳和 文件下載功能實(shí)現(xiàn)
相關(guān)文章
簡(jiǎn)單了解spring cloud 網(wǎng)關(guān)服務(wù)
這篇文章主要介紹了簡(jiǎn)單了解spring cloud 網(wǎng)關(guān)服務(wù),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10MyBatis圖文并茂講解注解開發(fā)一對(duì)多查詢
這篇文章主要介紹了SpringBoot中Mybatis注解一對(duì)多查詢的實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07Spring的兩種事務(wù)管理機(jī)制的基本概念和demo示例
Spring事務(wù)包括聲明式事務(wù)管理和注解式事務(wù)管理,我們通過(guò)概念和小demo的形式一步一步地來(lái)一起學(xué)習(xí)這個(gè)知識(shí)點(diǎn),需要的朋友可以參考下2023-07-07Java中spring boot 字符串判斷是否為空方法小結(jié)
這篇文章主要介紹了Java中spring boot字符串判斷是否為空,通過(guò)安裝依賴,結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2023-11-11基于Javamail實(shí)現(xiàn)發(fā)送郵件(QQ/網(wǎng)易郵件服務(wù)器)
這篇文章主要介紹了基于Javamail實(shí)現(xiàn)發(fā)送郵件,分別使用QQ郵箱作為smtp郵件服務(wù)器發(fā)送郵件,使用網(wǎng)易郵箱作為smtp郵件服務(wù)器發(fā)送郵件,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-08-08