Spring WEB实现DPF\GIF\ZIP等文件下载

x33g5p2x  于2022-09-17 转载在 Java  
字(2.7k)|赞(0)|评价(0)|浏览(302)

从 Spring Web 应用程序提供静态资源访问很简单,但是如果您需要从数据库或文件系统中获取文件怎么办呢?在这一集中,我们将了解如何从Spring控制器返回文件。

详细视频笔记

在这个例子中,我们将展示如何从类路径中读取 PDF,模拟从数据库或文件系统读取并从 RESTful Web 服务下载它。虽然我们使用 PDF,但您可以替换几乎任何文件格式,例如 gif、jpeg、tiff、png、zip、jars、wars、ear 或您需要流式传输到 browser 的任何其他二进制格式。

项目设置

访问 spring initializer website 并选择 web 项目依赖项,我们将创建一个 Spring Boot 骨架项目。在 eclipse 中打开项目,我们将一个名为 pdf-sample.pdf 的示例 pdf 复制到资源目录中。最后创建一个名为 DownloadPDFController@RestController,我们将存根到我们想要将请求映射到的方法中。

@RestController
public class DownloadPDFController {

}

创建请求方法

DownloadPDFController 中,我们将为应用程序创建一个默认请求映射。返回类型将是 ResponseEntity,它是添加 HttpStatus 代码的 HttpEntity 的扩展,类型为 InputStreamResource。接下来出于演示目的,我们使用 ClassPathResource 从类路径中获取一个名为 pdf-sample.pdf 的文件。这可以通过从网络驱动器读取文件或从数据库中检索文件来代替。一旦我们掌握了文件,我们就可以使用 Spring 4.1 中引入的 ResponseEntityBuilder 将响应的长度、内容类型和正文设置为文件。

让我们继续运行我们的示例并导航到 http://localhost:8080/ 以查看 pdf。

@RequestMapping(value = "/", method = RequestMethod.GET, produces = "application/pdf")
public ResponseEntity<InputStreamResource> downloadPDFFile()
        throws IOException {

    ClassPathResource pdfFile = new ClassPathResource("pdf-sample.pdf");

    return ResponseEntity
            .ok()
            .contentLength(pdfFile.contentLength())
            .contentType(
                    MediaType.parseMediaType("application/octet-stream"))
            .body(new InputStreamResource(pdfFile.getInputStream()));
}

防止缓存

[1:20]

通常,当您返回文档时,您可能希望阻止缓存,以便下次发出请求时返回最新版本。幸运的是,ResoponseEnity 允许您在响应中设置标头。我们将创建 HttpHeaders 对象设置 Cache-Control、Pragma 和 Expires 属性。如果您想防止在整个应用程序中进行缓存,您可以在 FilterHandlerInterceptor 中设置响应。

@RequestMapping(value = "/", method = RequestMethod.GET, produces = "application/pdf")
public ResponseEntity<InputStreamResource> downloadPDFFile()
        throws IOException {

    ClassPathResource pdfFile = new ClassPathResource("pdf-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");

    return ResponseEntity
            .ok()
            .headers(headers)
            .contentLength(pdfFile.contentLength())
            .contentType(MediaType.parseMediaType("application/octet-stream"))
            .body(new InputStreamResource(pdfFile.getInputStream()));
}

ByteArrayHttpMessageConverter

您可能需要注册一个名为 ByteArrayHttpMessageConverter 的自定义消息转换器。如果您使用的是 spring boot,您可以创建一个名为“customConverters”的 bean,创建 ByteArrayHttpMessageConverter 并填充一个 HttpMessageConverters 对象。

@SpringBootApplication
public class ReturnFileFromSpringRestWebserviceApplication {

    public static void main(String[] args) {
        SpringApplication.run(
                ReturnFileFromSpringRestWebserviceApplication.class, args);
    }

    @Bean
    public HttpMessageConverters customConverters() {
        ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
        return new HttpMessageConverters(arrayHttpMessageConverter);
    }
}

感谢阅读!

相关文章

微信公众号

最新文章

更多