更加优雅的下载文件 --- http header Content-Disposition 学习

更加优雅的下载文件 --- http header Content-Disposition 学习

Content-Disposition 在响应头中,告诉浏览器如何处理返回的内容,在表单提交中,说明表单字段信息。

在响应头中

用在响应头中,告诉浏览器如何处理返回的内容。

'Content-Disposition': 'inline'

预览,返回的内容替换当前页面,可使用 a 标签的 target="_blank" 打开新标签。

'Content-Disposition': 'attachment'

下载,使用 a 访问,会把路径作为名字,文件后缀名浏览器自动识别。

'Content-Disposition': 'attachment;filenam
### 如何在 Spring Boot 中实现文件下载 为了实现在 Spring Boot 应用程序中的文件下载功能,通常有两种主要方式:一种是通过 `HttpServletResponse` 流式传输文件给客户端;另一种则是利用 `ResourceLoader` 加载资源并返回。这两种方法都允许开发者灵活地控制要发送至用户的文件。 #### 方法一:使用 HttpServletResponse 实现文件下载 这种方式适用于直接读取服务器上的文件并通过 HTTP 响应流将其传递回浏览器或其他客户端应用的情况。下面展示了一个简单的控制器函数用于执行此操作: ```java import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @Controller public class FileDownloadController { @GetMapping("/downloadFile") public void download(HttpServletResponse response) throws IOException { String filePath = "path/to/your/file.ext"; // 文件路径 Path path = Paths.get(filePath); File file = new File(filePath); if (!file.exists()) { throw new RuntimeException("无法找到指定位置的文件"); } response.setContentType(Files.probeContentType(path)); response.setContentLength((int) Files.size(path)); response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); try (FileInputStream inputStream = new FileInputStream(file)) { int length; byte[] buffer = new byte[1024 * 8]; while ((length = inputStream.read(buffer)) != -1){ response.getOutputStream().write(buffer, 0, length); } } catch (IOException e) { throw new RuntimeException(e.getMessage()); } response.flushBuffer(); } } ``` 这种方法简单明了,适合于大多数场景下的文件下载需求[^1]。 #### 方法二:基于 Resource 接口的方式 当需要更优雅地处理静态资源或配置化的文件路径时,推荐使用 `org.springframework.core.io.Resource` 和其子类配合 `ResponseEntity<Resource>` 来构建响应体。这不仅简化了编码过程,还提高了代码可维护性和扩展性。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.InputStreamResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import java.io.ByteArrayInputStream; import java.util.Arrays; @Controller class DownloadController { private final ResourceLoader resourceLoader; @Autowired public DownloadController(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } @GetMapping("/resource-download") ResponseEntity<InputStreamResource> serveFile() { try { Resource resource = resourceLoader.getResource("classpath:/static/sample.pdf"); // 或者其他形式定位资源 HttpHeaders headers = new HttpHeaders(); headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); headers.add("Pragma", "no-cache"); headers.add("Expires", "0"); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=sample.pdf"); return ResponseEntity.ok() .headers(headers) .contentLength(resource.contentLength()) .contentType(MediaType.parseMediaType("application/pdf")) .body(new InputStreamResource(resource.getInputStream())); } catch (Exception ex) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } } ``` 上述例子展示了如何加载位于 ClassPath 下名为 sample.pdf 的 PDF 文档作为附件供用户下载。对于不同类型的文件只需调整 MIME 类型即可适应各种情况[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值