ToB企服应用市场:ToB评测及商务社交产业平台

标题: 后端接口返回文件流,前端下载(java+vue) [打印本页]

作者: 守听    时间: 2024-10-13 13:47
标题: 后端接口返回文件流,前端下载(java+vue)

     各位小伙伴们大家好,欢迎来到这个小扎扎的专栏 总结 | 提效 | 拓展,在这个系列专栏中记录了博主在学习期间总结的大块知识点,以及日常工作中碰到的各种技术点 ┗|`O′|┛

   
   
    本身前端是可以直接通过文件的url对文件进行下载的,但是在进行业务对接开发的时候,前端没有获取文件下载的权限,以是需要后端获取文件之后把得到的文件流传给前端,前端通过文件流下载文件。
后端获取

controller层
  1. /**
  2. * 根据附件id返回文件流
  3. */
  4. @ApiOperation(value = "根据附件id返回文件流", notes = "传入附件id")
  5. @PostMapping(value = "/getByFileId")
  6. public void getByFileId(HttpServletResponse response, @RequestBody FileIdReq fileIdReq) {
  7.     matterBasicInfoService.getByFileId(response, fileIdReq.getFileId());
  8. }
复制代码
service接口
  1. void getByFileId(HttpServletResponse response, String fileId);
复制代码
实现类
  1. @Override
  2. public void getByFileId(HttpServletResponse response, String fileId) {
  3.     // 获取附件详情  主要是要附件的url和名字
  4.     MatterAttachmentFormOdr matterAttachmentFormOdr = matterAttachmentFormOdrService.getById(fileId);
  5.     log.error("matterAttachmentFormOdr-----:{}", matterAttachmentFormOdr);
  6.     if (BeanUtil.isEmpty(matterAttachmentFormOdr) || StrUtil.isBlank(matterAttachmentFormOdr.getUrl())) {
  7.         throw new BusinessValidationException("该文件不存在");
  8.     }
  9.    
  10.     // 附件url替换  如果url可以直接下载的话可以跳过这一步
  11.     String filePath = matterAttachmentFormOdr.getUrl().replace("......", "......");
  12.     log.error("filePath-----:{}", filePath);
  13.     ServletOutputStream out = null;
  14.     InputStream inputStream = null;
  15.     try {
  16.         //与服务器建立连接
  17.         URL url = new URL(filePath);
  18.         URLConnection conn = url.openConnection();
  19.         inputStream = conn.getInputStream();
  20.         try {
  21.             //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
  22.             response.setContentType("multipart/form-data");
  23.             response.addHeader("Content-Disposition", "attachment; filename=" + matterAttachmentFormOdr.getName());
  24.         } catch (Exception e){
  25.             e.printStackTrace();
  26.         }
  27.         out = response.getOutputStream();
  28.         // 读取文件流
  29.         int len = 0;
  30.         byte[] buffer = new byte[1024 * 10];
  31.         while ((len = inputStream.read(buffer)) != -1) {
  32.             out.write(buffer, 0, len);
  33.         }
  34.         log.error("读取文件流结束。。。。。。。");
  35.     } catch (Exception e){
  36.         e.printStackTrace();
  37.     } finally {
  38.         try {
  39.             if (out != null) {
  40.                 out.flush();
  41.                 out.close();
  42.             }
  43.             if (inputStream != null) {
  44.                 inputStream.close();
  45.             }
  46.         } catch (IOException e) {
  47.             throw new RuntimeException(e);
  48.         }
  49.     }
  50. }
复制代码
前端下载

  1. handleGetFile(file) {
  2.   const type = file.url.split('.')['1']
  3.   if (!file.id) {
  4.     this.$Message.warning('文件下载失败!')
  5.     return
  6.   }
  7.   // 定义参数
  8.   const data = {
  9.     data: {
  10.       fileId: file.id,
  11.     },
  12.     access_token: xxxxxx,
  13.   }
  14.   // 调用后端接口
  15.   this.$store.dispatch('comprehensive/getByFileId', data).then(res => {
  16.     this.$Message.loading(`正在下载${file.name}数据`)
  17.     const applicationType = this.getFileTypeMime(type)
  18.     const blob = new Blob([res.data], { type: applicationType })
  19.     const link = document.createElement('a')
  20.    
  21.     const href = window.URL.createObjectURL(blob) // 创建下载的链接
  22.     link.href = href
  23.     link.download = `${file.name}` // 下载后文件名
  24.     document.body.appendChild(link)
  25.     link.click() // 点击下载
  26.     document.body.removeChild(link) // 下载完成移除元素
  27.     window.URL.revokeObjectURL(href) // 释放掉blob对象
  28.   })
  29. },
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4