用ajax下载字节流形式的excel文件

原因:ajax请求只是个“字符型”的请求,即请求的内容是以文本类型存放的。文件的下载是以二进制形式进行的,ajax没法解析后台返回的文件流,所以无法处理二进制流response输出来下载文件。

解决方法:使用form表单提交实现文件下载

1,后台代码实现方法:

复制代码
// 生成excel文件
    @RequestMapping(value = "/study", method = RequestMethod.POST)
    public void study(@RequestBody ParamVO paramVO, HttpServletResponse response) throws UnsupportedEncodingException {
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" + new String(paramVO.getFileName().getBytes("utf-8"), "iso-8859-1"));
        try (ByteArrayOutputStream bos = templateService.excel(paramVO);
                BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream())) {
            out.write(bos.toByteArray());
            response.setHeader("Content-Length", String.valueOf(bos.toByteArray().length));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
复制代码

2,前端页面使用Ajax下载文件

复制代码
var xhr = new XMLHttpRequest();
        xhr.open('post', 'http://localhost:8080/user/export', true);
        xhr.responseType = 'blob';
        xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
        xhr.onload = function () {
            if (this.status == 200) {
                var blob = this.response;
                var a = document.createElement('a');
                var url = window.URL.createObjectURL(blob);
                a.href = url;
                //设置文件名称
                a.download = '用户信息.xls';
                a.click();
            }
        }
        xhr.send(JSON.stringify({
           "type" : 1,
           "startDate" : "2018-01-01",
           "endDate" : "2018-12-31"
        }));
    }
复制代码

或者前端也可以这样实现:

复制代码
{
        var xhr = new XMLHttpRequest();
      xhr.open('post', 'http://localhost:8080/user/export', true);
      xhr.responseType = 'blob';
      xhr.onload = function () {
      var blob = this.response;
      if(window.navigator.msSaveOrOpenBlob){
          window.navigator.msSaveBlob(blob, 'msSaveBlob_testFile.txt');
      }else{
          var link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = 'msSaveBlob_testFile.txt';
          link.click();
          window.URL.revokeObjectURL(link.href);
      }
      xhr.send(null);
      }
}
复制代码

 

本文转自:https://blog.csdn.net/hj7jay/article/details/86309968

posted @   ppjj  阅读(11251)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2018-03-14 Spring整合redis,通过sentinel进行主从切换
2018-03-14 Redis Sentinel的Redis集群(主从&Sharding)高可用方案
2018-03-14 eclipse配置xml的自动提示
2017-03-14 Mockito - Wanted but not invoked: Actually, there were zero interactions with this mock
点击右上角即可分享
微信分享提示