axios+springboot下载文件

本文档展示了如何使用axios从后端下载文件。前端部分通过创建隐藏的a标签,设置下载属性,并利用blob对象创建URL来触发文件下载。后端使用Spring MVC返回ResponseEntity,设置相应头信息,确保文件正确下载。
摘要由CSDN通过智能技术生成
downloadFile() {
      let path = this.chosenItem.path
      let filename = this.chosenItem.name
      axios.get('/download', {params: {path}, responseType: 'blob'}).then(res => {
        let eleLink = document.createElement('a');
        eleLink.download = filename;
        eleLink.style.display = 'none';
        // 字符内容转变成blob地址
        let blob = new Blob([res.data]);
        eleLink.href = URL.createObjectURL(blob);
        // 触发点击
        document.body.appendChild(eleLink);
        eleLink.click();
        // 然后移除
        document.body.removeChild(eleLink);
      })
    }

@GetMapping("/download")
    public ResponseEntity<FileSystemResource> download(@RequestParam String path) {
        System.out.println(path);
        File file = fileBasicService.download(path);
        String fileName = file.getName();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", String.format("attachment;filename=\"%s", fileName));
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Last-Modified", new java.util.Date().toString());
        headers.add("ETag", String.valueOf(System.currentTimeMillis()));

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new FileSystemResource(file));
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值