zoukankan      html  css  js  c++  java
  • Spring MVC 优雅下载和文件名正常显示(转载)

    https://blog.csdn.net/jiaobuchong/article/details/84641668

    使用 Spring MVC 的 ResponseEntity 传入文件的字节码即可实现下载功能,不用往HttpServletResponse response 的输出流写字节了。

    public class BasicController {
        protected ResponseEntity<byte[]> getFile(String fileName, byte[] dataArray) throws Exception {
            fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition", "attachment; filename="" + fileName + ""; filename*=utf-8''" + fileName);
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            return ResponseEntity
                    .ok()
                    .headers(headers)
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(dataArray);
        }
    
        protected ResponseEntity<byte[]> getExcelFile(String fileName, byte[] dataArray) throws Exception {
    //        fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
            // Safari 和 Chrome 都可以正常下载包含中文文件名的 excel 文件
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition", "attachment; filename="" + fileName + ""; filename*=utf-8''" + fileName);
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            headers.add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            return ResponseEntity
                    .ok()
                    .headers(headers)
                    .body(dataArray);
        }
    }
    

      getFile 方法在 Safari 浏览器不能正常下载 Excel 文件,下载的是一个后缀名为 .dms 文件。getExcelFile 指定 Excel 的 MIME 类型,并将文件名编码为 ISO_8859_1,兼容 Chrome 和 Safari 的下载。

    @RestController
    public class FileProcessController extends BasicController {
        @GetMapping("/test/download")
        public ResponseEntity<byte[]> downloadFile(d) throws Exception {
        	 // 得到文件的字节数组 
        	 byte[] dataArray = getData(); 
            return this.getExcelFile("excel-文件下载.xlsx", dataArray);
        }
    }
    

      在浏览器里模拟一下:

    Spring MVC 文件下载测试: <a href="http://localhost:8080/test/download">点击下载</a>
    

      

     

  • 相关阅读:
    [SQL server] IF ELSE 和 CASE WHEN 的用法
    SQL server游标基本结构
    SQLserver查看某个视图的创建语句
    SqlServer和Oracle修改表结构语句
    IE浏览器部分js代码不生效的问题
    SQL server将查询到的多行结果,拼接成字符串(列转行)
    SQL server将某个字符串将按指定字符分解成子字符串(行转列)
    安装weblogic时,运行configure.cmd报错、闪退、无法创建域
    黑苹果相关工具
    黑苹果安装问题集
  • 原文地址:https://www.cnblogs.com/lzh1043060917/p/14122099.html
Copyright © 2011-2022 走看看