axios+SpringBoot实现文件下载

前端代码

xaizai(){
      axios({
        method: "GET",
        url: url,
        responseType:'blob', //返回是个文件
      }).then(response => {
        console.log(response) //then直接下载,方法在下边
        this.download(response)
      })
    },
    download (res) {
      let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });//type是文件类,详情可以参阅blob文件类型
      // 创建新的URL并指向File对象或者Blob对象的地址
      const blobURL = window.URL.createObjectURL(blob)
      // 创建a标签,用于跳转至下载链接
      const tempLink = document.createElement('a')
      tempLink.style.display = 'none'
      tempLink.href = blobURL
      tempLink.setAttribute('download', decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1]))
      // 兼容:某些浏览器不支持HTML5的download属性
      if (typeof tempLink.download === 'undefined') {
        tempLink.setAttribute('target', '_blank')
      }
      // 挂载a标签
      document.body.appendChild(tempLink)
      tempLink.click()
      document.body.removeChild(tempLink)
      // 释放blob URL地址
      window.URL.revokeObjectURL(blobURL)
    }

后端代码

	@GetMapping("/download")
    public void getFile(HttpServletResponse response) throws Exception{
    	//new File()  括号里存放的是路径,可以换成自己的
        File readFile = new File(System.getProperty("user.dir") + File.separator + "物流用户信息导入模板.xlsx");
        //字节流-用于读文件  这里只是demo用的非缓冲流。实际项目可以用BufferedInputStream。 此功能是读取图片,所以用的字节流。如果是文本的话可以用字符流效率高,具体类看下面注释
        //        BufferedReader bufferedReader = new BufferedReader(new FileReader(readFile));//字符流
        FileInputStream fileInputStream = new FileInputStream(readFile);//字节流
        //设置文件下载方式
        response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode("物流用户信息导入模板.xlsx","utf-8"));
        //获取servlet响应输出字节流
        //        PrintWriter writer = response.getWriter();//字符流
        ServletOutputStream outputStream = response.getOutputStream(); //字节流

        //流数据交换,每次交换10k数据大小 (1024k = 1m)
        byte[] bytes = new byte[1024*10];
        int read;
        do {
            read = fileInputStream.read(bytes);
            outputStream.write(bytes,0,read);
        }while (-1 != read);

        //关闭资源
        IOUtils.closeQuietly(fileInputStream);
        IOUtils.closeQuietly(outputStream);
    }

亲测可以使用,如果写后端直接复制后端,如果写前端直接复制前端,有问题可以评论找我

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值