若依框架下载文件

若依下载的逻辑是指定文件存储的路径,在ruoyi-admin模块下的application.yml中配置,路径结尾必须要加'/'或者'\'结尾。
他使用的是虚拟路径映射,所以文件名必须是配置路径下真实的文件名。

若依采用的是流的方式,前端必须要用bolb的方式去接收,然后保存成本地文件

后端代码

参数一:配置路径下,真实的文件名。

参数二:是否下载后删除,false不删除。

    @Autowired
    RuoYiConfig RuoYiConfig;

    @GetMapping("/downloadZip")
    public void fileDownload(@RequestParam String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            System.out.println("文件名称:" + fileName);
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.format("下载文件失败", e);
        }
    }

 前端代码

import request from '@/utils/request'

export const publishExportTemplateFile = (res, name, type = false) => {
  let url;
  if (type) {
    url = window.URL.createObjectURL(new Blob([res], {type: 'application/zip'}));
  } else {
    url = window.URL.createObjectURL(new Blob([res]));
  }
  // const url = window.URL.createObjectURL(new Blob([res]));
  const link = document.createElement('a');
  link.style.display = 'none';
  link.href = url;
  link.setAttribute('download', name);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

export function downloadFile(filePath) {
  request({
    url: '/projectAch/pages/downloadZip',
    method: 'get',
    params: {fileName: filePath, delete: false},
    responseType: 'blob' // 设置响应类型为 blob
  })
    .then(response => {
      publishExportTemplateFile(response ,filePath);
    })
    .catch(error => {
      console.error('Download file failed:', error);
    });
}

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值