在SpringBoot项⽬中实现⽂件下载功能
(⼀)需求
在您的 springboot 项⽬中,可能会存在让⽤户下载⽂档的需求,⽐如让⽤户下载 readme ⽂档来更好地了解该项⽬的概况或使⽤⽅法。所以,您需要为⽤户提供可以下载⽂件的 API ,将⽤户希望获取的⽂件作为下载资源返回给前端。
(⼆)代码
maven 依赖
请您创建好⼀个 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
在您的 l 中,进⾏如下属性配置:
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 类绑定,也就是将 l 中的 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 类,这意味着返回内容为 io 流资源;并在返回体头部添加附件,以便于前端页⾯下载⽂件。
@RestController
springboot框架的作用@RequestMapping("file")
public class FileController {
private static final Logger logger = Logger(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 = ServletContext().File().getAbsolutePath());
}catch(IOException e){
<("⽆法获取⽂件类型", e);
}
if(contentType == null){
contentType ="application/octet-stream";
}
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(contentType))
.header(HttpHeaders.CONTENT_DISPOSITION,"attachment; filename=\""+ Filename()+"\"")
.body(resource);
}
}
服务层
服务层的主要⼯作是把⽂件作为 IO 资源加载。注意,在 Service 实现类的构造⽅法中要使⽤ @Autowired 注⼊前⾯定义好的属性绑定类FileProperties.
@Service
public class FileServiceImpl implements FileService {
private final Path filePath;
@Autowired
public FileServiceImpl(FileProperties fileProperties){
filePath = (DocDir()).toAbsolutePath().normalize();
}
@Override
public Resource loadFileAsResource(String fileName){
Path path = solve(fileName).normalize();
try{
UrlResource resource =new Uri());
ists()){
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 属性来规定这是⼀个下载⽂件。
<a href="/file/download/readme.pdf"download>下载使⽤⼿册</a>
(三)参考博客
更多关于 springboot 项⽬上传、下载⽂件的功能请参考:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。