在 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)站的支持!
如果你覺得本文對(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)文章
Java那點(diǎn)兒事之Map集合不為人知的秘密有哪些
Map用于保存具有映射關(guān)系的數(shù)據(jù),Map集合里保存著兩組值,一組用于保存Map的key,另一組保存著Map的value,和查字典類似,通過(guò)key找到對(duì)應(yīng)的value,通過(guò)頁(yè)數(shù)找到對(duì)應(yīng)的信息。用學(xué)生類來(lái)說(shuō),key相當(dāng)于學(xué)號(hào),value對(duì)應(yīng)name,age,sex等信息。用這種對(duì)應(yīng)關(guān)系方便查找2021-10-10
SpringBoot使用spring.factories加載默認(rèn)配置的實(shí)現(xiàn)代碼
在日常開發(fā)過(guò)程中,發(fā)布一些產(chǎn)品或者框架時(shí),會(huì)遇到某些功能需要一些配置才能正常運(yùn)行,這時(shí)我們需要的提供默認(rèn)配置項(xiàng),同時(shí)用戶也能覆蓋進(jìn)行個(gè)性化2024-06-06
實(shí)例解析Java設(shè)計(jì)模式編程中的適配器模式使用
適配器模式的主要作用是在新接口和老接口之間進(jìn)行適配,通過(guò)將一個(gè)類的接口轉(zhuǎn)換成客戶期望的另一個(gè)接口,讓原本不兼容的接口可以合作無(wú)間,本文以實(shí)例解析Java設(shè)計(jì)模式編程中的適配器模式使用,需要的朋友可以參考下2016-05-05
踩坑之spring事務(wù),非事務(wù)方法與事務(wù)方法執(zhí)行相互調(diào)用方式
這篇文章主要介紹了踩坑之spring事務(wù),非事務(wù)方法與事務(wù)方法執(zhí)行相互調(diào)用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07
解決RestTemplate加@Autowired注入不了的問(wèn)題
這篇文章主要介紹了解決RestTemplate加@Autowired注入不了的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。2021-08-08
SpringBoot實(shí)現(xiàn)EMQ設(shè)備的上下線告警
EMQX?的上下線系統(tǒng)消息通知功能在客戶端連接成功或者客戶端斷開連接,需要實(shí)現(xiàn)設(shè)備的上下線狀態(tài)監(jiān)控,所以本文給大家介紹了如何通過(guò)SpringBoot實(shí)現(xiàn)EMQ設(shè)備的上下線告警,文中有詳細(xì)的代碼示例,需要的朋友可以參考下2023-10-10
相冊(cè)管理系統(tǒng)(Java表單+xml數(shù)據(jù)庫(kù)存儲(chǔ))
這篇文章主要為大家詳細(xì)介紹了相冊(cè)管理系統(tǒng)的實(shí)現(xiàn)步驟,Java表單的文件上傳和下載,xml數(shù)據(jù)庫(kù)存儲(chǔ)信息,感興趣的小伙伴們可以參考一下2016-07-07

