SpringBoot项目中怎么实现文件下载功能
创始人
2024-12-22 18:21:30
0次

maven 依赖

请您创建好一个 springboot 项目,一定要引入 web 依赖:

 org.springframework.boot  spring-boot-starter-web

建议引入 thymeleaf 作为前端模板:

 org.springframework.boot  spring-boot-starter-thymeleaf

配置 application

在您的 application.yml 中,进行如下属性配置:

file: doc-dir: doc/

该路径就是待下载文件存放在服务器上的目录,为相对路径,表示与当前项目(jar包)的相对位置。

将属性与 pojo 类自动绑定

springboot 中的注解 @ConfigurationProperties 可以将 application 中定义的属性与 pojo 类自动绑定。所以,我们需要定义一个 pojo 类来做 application 中 file.doc-dir=doc/ 的配置绑定:

@ConfigurationProperties(prefix = "file")@Datapublic 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 类,这意味着返回内容为 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 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 实现类的构造方法中要使用 @Autowired 注入前面定义好的属性绑定类 FileProperties.

@Servicepublic 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 属性来规定这是一个下载文件。

下载使用手册

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...