• SpringBoot的文件下载


    SpringBoot的文件下载

    SpringBoot的文件下载方法有很多,此处只记录使用Spring的Resource实现类FileSystemResource做下载,其余实现类照葫芦画瓢即可。 
    直接上干货

    1、下载部分代码

        public ResponseEntity<FileSystemResource> export(File file) {
            if (file == null) {
                return null;
            }
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition", "attachment; filename=" + System.currentTimeMillis() + ".xls");
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            return ResponseEntity
                    .ok()
                    .headers(headers)
                    .contentLength(file.length())
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(new FileSystemResource(file));
        }

    这段代码,我是封装在BaseController.class,其他的Controller继承该类,就可直接调用父类的下载方法,service只需要提供文件file即可。

    2、实例展示

    @RestController
    @RequestMapping(value = "/order", method = RequestMethod.POST)
    public class OrderController extends BaseController {
    
        @Autowired
        private IOrderService orderService;
    
        @RequestMapping(value = "/export")
        public ResponseEntity<FileSystemResource> listExport(String proNo) {
            File file = orderService.listExport(proNo);
            return export(file);
        }
        }

    注意:此处使用的下载返回是FileSystemResource,所以service提供的是File。
    以下是百度到的Resource其它实现类,引用来自http://elim.iteye.com/blog/2016305

    ClassPathResource 可用来获取类路径下的资源文件。假设我们有一个资源文件test.txt在类路径下,我们就可以通过给定对应资源文件在类路径下的路径path来获取它,new ClassPathResource(“test.txt”)。 
    FileSystemResource可用来获取文件系统里面的资源。我们可以通过对应资源文件的文件路径来构建一个FileSystemResource。FileSystemResource还可以往对应的资源文件里面写内容,当然前提是当前资源文件是可写的,这可以通过其isWritable()方法来判断。FileSystemResource对外开放了对应资源文件的输出流,可以通过getOutputStream()方法获取到。 
    UrlResource可用来代表URL对应的资源,它对URL做了一个简单的封装。通过给定一个URL地址,我们就能构建一个UrlResource。 
    ByteArrayResource是针对于字节数组封装的资源,它的构建需要一个字节数组。 
    ServletContextResource是针对于ServletContext封装的资源,用于访问ServletContext环境下的资源。ServletContextResource持有一个ServletContext的引用,其底层是通过ServletContext的getResource()方法和getResourceAsStream()方法来获取资源的。 
    InputStreamResource是针对于输入流封装的资源,它的构建需要一个输入流。

  • 相关阅读:
    聊聊Senior .net 面试,作为面试官你称职吗
    使用Microsoft BizTalk Adapter for mySAP Business Suite需要注意的一些限制点
    eos账号管理
    如何安装以太坊钱包Parity
    Infoq主办 Baidu Web 开发者大会记录
    http请求的详细过程转载
    php 下载保存文件保存到本地
    php section
    用javascript拼接html代码标签
    php使用sql数据库 取得字段问题
  • 原文地址:https://www.cnblogs.com/hfultrastrong/p/9259876.html
Copyright © 2020-2023  润新知