若依框架,vue+elementPlus+springboot实现文件下载功能

前端:调用该方法实现文件下载,前端你可以写个按钮调用该方法

async function submit() {
  for (const id of form.value.fileList) {
    const baseURL = import.meta.env.VITE_APP_BASE_API
    var url = baseURL + `/download/${id}`//写你自己的文件下载接口
    axios({
      method: 'get',
      url: url,
      responseType: 'blob',
      headers: { 'Authorization': 'Bearer ' + getToken() }
    }).then((res) => {
      const isBlob = blobValidate(res.data);
      if (isBlob) {
        const blob = new Blob([res.data])
        saveAs(blob, decodeURIComponent(res.headers['download-filename']))
      } else {
        this.printErrMsg(res.data);
      }
    })
  }
  close();
}

后端:service层


    public void downloadFile(String id, HttpServletResponse response){
        try
        {
            Assert.notNull(id,()->new ServiceException("数据异常,请联系管理员"));
            //获取该文件信息
            FileInfo fileInfo = fileInfoService.getById(Long.parseLong(id));
            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
            // 数据库资源地址
            String downloadPath = (localPath + fileInfo.getFilePath()).replace("/profile","");
            // 下载名称
            String downloadName = fileInfo.getName();
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            //文件名(文件001_20240516140426A003.xlsx)
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            //文件路径(/profile/upload/2024/05/16/文件001_20240516140426A003.xlsx)
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值