vue+Springboot实现文件下载

一、Vue部分

methods:{
	download() {
        axios({
          url: 'http://10.57.20.90:8083/dealer/download',
          method: 'GET',
          responseType: 'blob', // 重要:指定响应类型为 blob
        })
          .then((response) => {
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', '经销商导入模板.xlsx'); // 设置下载文件名
            document.body.appendChild(link);
            link.click(); // 触发下载
            document.body.removeChild(link); // 下载后移除链接
            window.URL.revokeObjectURL(url); // 释放内存
          })
          .catch((error) => {
            console.error('下载失败', error);
          });
      },
}

二、Springboot部分(使用类路径的方式获取文件路径,在打jar包上传服务器后,避免了找不到文件的问题,该代码是jdk1.8的实现方法)

@GetMapping("download")
    public ResponseEntity<ByteArrayResource> download() {
        try (InputStream inputStream = getClass().getResourceAsStream("/com/szc/suppliermanagement/file/经销商模板.xlsx");
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {

            if (inputStream == null) {
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            byte[] bytes = outputStream.toByteArray();
            ByteArrayResource resource = new ByteArrayResource(bytes);

            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attachment; filename=经销商模板.xlsx");

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);
        } catch (IOException e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值