ajax方式下载文件

前端采用异步方式请求
       

 axios({
          method: 'POST',
          url: this.downTemplateUrl,
          params: {
            type: 1
          },
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          responseType: 'blob'
        }).then(res => {
          let blob = new Blob([res.data], {type: "application/vnd.ms-excel;charset=UTF-8"});
          if (window.navigator && window.navigator.msSaveOrOpenBlob) { // IE
            window.navigator.msSaveOrOpenBlob(blob, fileName)
          } else {
            let objectUrl = (window.URL || window.webkitURL).createObjectURL(blob)
            let downFile = document.createElement('a')
            downFile.style.display = 'none'
            downFile.href = objectUrl
            downFile.download = fileName // 下载后文件名
            document.body.appendChild(downFile)
            downFile.click()
            document.body.removeChild(downFile) // 下载完成移除元素
            // window.location.href = objectUrl
            window.URL.revokeObjectURL(objectUrl)   // 只要映射存在,Blob就不能进行垃圾回收,因此一旦不再需要引用,就必须小心撤销URL,释放掉blob对象。
          }
        }).catch(err=>{
          console.log(err)
        })
      },

后端返回文件流:

public void downloadFile(HttpServletResponse response, String result) {
        OutputStream os = null;
        try {
            response.setCharacterEncoding("UTF-8");
            String path = SecurityTools.decrypt(result);
            //response.setContentType("application/octet-stream");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            String fileName = path.substring(path.lastIndexOf("/") + 1);
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            os = response.getOutputStream();
            File file = new File(path);
            final int length = 1024 * 1024;
            ByteBuffer bytes = ByteBuffer.allocate(length);
            SeekableByteChannel seekByte = Files.newByteChannel(file.toPath());
            int read = -1;
            while ((read = seekByte.read(bytes)) >= 1) {
                os.write(bytes.array(), 0, read);
                os.flush();
                bytes.clear();
            }
        } catch (Exception e) {
            log.error("下载失败," + e.getCause().getMessage());
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值