当前位置:   article > 正文

若依框架下载文件_若依文件下载

若依文件下载

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

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

后端代码

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

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

  1. @Autowired
  2. RuoYiConfig RuoYiConfig;
  3. @GetMapping("/downloadZip")
  4. public void fileDownload(@RequestParam String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
  5. try {
  6. System.out.println("文件名称:" + fileName);
  7. if (!FileUtils.checkAllowDownload(fileName)) {
  8. throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName));
  9. }
  10. String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
  11. String filePath = RuoYiConfig.getDownloadPath() + fileName;
  12. response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
  13. FileUtils.setAttachmentResponseHeader(response, realFileName);
  14. FileUtils.writeBytes(filePath, response.getOutputStream());
  15. if (delete) {
  16. FileUtils.deleteFile(filePath);
  17. }
  18. } catch (Exception e) {
  19. e.printStackTrace();
  20. System.out.format("下载文件失败", e);
  21. }
  22. }

 前端代码

  1. import request from '@/utils/request'
  2. export const publishExportTemplateFile = (res, name, type = false) => {
  3. let url;
  4. if (type) {
  5. url = window.URL.createObjectURL(new Blob([res], {type: 'application/zip'}));
  6. } else {
  7. url = window.URL.createObjectURL(new Blob([res]));
  8. }
  9. // const url = window.URL.createObjectURL(new Blob([res]));
  10. const link = document.createElement('a');
  11. link.style.display = 'none';
  12. link.href = url;
  13. link.setAttribute('download', name);
  14. document.body.appendChild(link);
  15. link.click();
  16. document.body.removeChild(link);
  17. }
  18. export function downloadFile(filePath) {
  19. request({
  20. url: '/projectAch/pages/downloadZip',
  21. method: 'get',
  22. params: {fileName: filePath, delete: false},
  23. responseType: 'blob' // 设置响应类型为 blob
  24. })
  25. .then(response => {
  26. publishExportTemplateFile(response ,filePath);
  27. })
  28. .catch(error => {
  29. console.error('Download file failed:', error);
  30. });
  31. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/438756
推荐阅读
相关标签
  

闽ICP备14008679号