前端vue从后端springboot下载指定文件

本文介绍了如何在前端Vue应用中通过调用后端Spring Boot接口来实现指定文件的下载。详细阐述了前端Vue的请求处理和后端Spring Boot的文件服务实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前端vue从后端springboot下载指定文件

前端接口:

downloadTemplate(){
  return request({
    url: '/api/v1/weekprofit/downloadtemplate',
    method: 'post',
    responseType: 'blob'
  })
}

vue代码:

downloadTemplate() {
  weeklyProfitAPI.downloadTemplate().then( res => {
      const data = res.data;
      let url = window.URL.createObjectURL(new Blob([data]));
      let link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      link.setAttribute('download', '文件名');
      document.body.appendChild(link);
      link.click();
  });
},

后端代码:

    @PostMapping(value = "/downloadtemplate")
    public void downloadFile(HttpServletResponse response,HttpServletRequest request) {
        String path = "路径";
        String fileName = "文件名";
        String filePath = path + "\\" + fileName;
        File file = new File(filePath);

        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader(
                "Content-disposition",
                "attachment; filename="+fileName);
        try(
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                // 输出流
                BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
        ){
            byte[] buff = new byte[1024];
            int len = 0;
            while ((len = bis.read(buff)) > 0) {
                bos.write(buff, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值