• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

在 Spring Boot 项目中实现文件下载功能

springboot 搞代码 4年前 (2022-01-09) 43次浏览 已收录 0个评论

(一)需求

在您的 springboot 项目中,可能会存在让用户下载文档的需求,比如让用户下载 readme 文档来更好地了解该项目的概况或使用方法。

所以,您需要为用户提供可以下载文件的 API ,将本文来源gaodai$ma#com搞$代*码网2用户希望获取的文件作为下载资源返回给前端。

(二)代码

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

在您的 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 类,这意味着返回内容为 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);
  }
}

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:在 Spring Boot 项目中实现文件下载功能

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址