当前位置: 首页 > article >正文

后端接口返回文件流,前端下载(java+vue)

在这里插入图片描述

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

?? 内容速览

  • 后端获取
  • 前端下载

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

后端获取

controller层

/**
 * 根据附件id返回文件流
 */
@ApiOperation(value = "根据附件id返回文件流", notes = "传入附件id")
@PostMapping(value = "/getByFileId")
public void getByFileId(HttpServletResponse response, @RequestBody FileIdReq fileIdReq) {
    matterBasicInfoService.getByFileId(response, fileIdReq.getFileId());
}

service接口

void getByFileId(HttpServletResponse response, String fileId);

实现类

@Override
public void getByFileId(HttpServletResponse response, String fileId) {
    // 获取附件详情  主要是要附件的url和名字
    MatterAttachmentFormOdr matterAttachmentFormOdr = matterAttachmentFormOdrService.getById(fileId);
    log.error("matterAttachmentFormOdr-----:{}", matterAttachmentFormOdr);

    if (BeanUtil.isEmpty(matterAttachmentFormOdr) || StrUtil.isBlank(matterAttachmentFormOdr.getUrl())) {
        throw new BusinessValidationException("该文件不存在");
    }
    
    // 附件url替换  如果url可以直接下载的话可以跳过这一步
    String filePath = matterAttachmentFormOdr.getUrl().replace("......", "......");
    log.error("filePath-----:{}", filePath);

    ServletOutputStream out = null;
    InputStream inputStream = null;
    try {
        //与服务器建立连接
        URL url = new URL(filePath);
        URLConnection conn = url.openConnection();
        inputStream = conn.getInputStream();
        try {
            //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
            response.setContentType("multipart/form-data");
            response.addHeader("Content-Disposition", "attachment; filename=" + matterAttachmentFormOdr.getName());
        } catch (Exception e){
            e.printStackTrace();
        }
        out = response.getOutputStream();
        // 读取文件流
        int len = 0;
        byte[] buffer = new byte[1024 * 10];
        while ((len = inputStream.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        log.error("读取文件流结束。。。。。。。");
    } catch (Exception e){
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.flush();
                out.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

前端下载

handleGetFile(file) {
  const type = file.url.split('.')['1']
  if (!file.id) {
    this.$Message.warning('文件下载失败!')
    return
  }

  // 定义参数
  const data = { 
    data: {
      fileId: file.id,
    },
    access_token: xxxxxx,
  }

  // 调用后端接口
  this.$store.dispatch('comprehensive/getByFileId', data).then(res => {
    this.$Message.loading(`正在下载${file.name}数据`)
    const applicationType = this.getFileTypeMime(type)
    const blob = new Blob([res.data], { type: applicationType })
    const link = document.createElement('a')
    
    const href = window.URL.createObjectURL(blob) // 创建下载的链接
    link.href = href
    link.download = `${file.name}` // 下载后文件名
    document.body.appendChild(link)
    link.click() // 点击下载
    document.body.removeChild(link) // 下载完成移除元素
    window.URL.revokeObjectURL(href) // 释放掉blob对象
  })
},

http://www.kler.cn/a/451480.html

相关文章:

  • 特殊的“Undefined Reference xxx“编译错误
  • Rust 在前端基建中的使用
  • 深度学习在灾难恢复中的作用:智能运维的新时代
  • 【数据结构】数据结构整体大纲
  • 面试题整理18----Pause容器的用途
  • 代码随想录 day52 第十一章 图论part03
  • 医疗行业 UI 设计系列合集(一):精准定位
  • 【AI驱动的数据结构:包装类的艺术与科学】
  • 如何学习Trustzone
  • Linux下载RabbitMQ,并解决Github拒绝访问443的问题
  • 【仓颉语言体验】Hello World TCP客户端 C/C++ or Python
  • ResEmoteNet论文阅读与推理
  • 【可视化开源性能压测工具】小巧而强大的oha
  • 【数据结构2】线性表——顺序表
  • 动态规划:石子合并 图文+举例超详细说明
  • OpenCV相机标定与3D重建(26)计算两个二维点集之间的部分仿射变换矩阵(2x3)函数 estimateAffinePartial2D()的使用
  • AWTK 在树莓派 pico 上的移植笔记
  • HTMLCSSJavaScriptDOM 之间的关系?
  • 组态页面渲染器通过npm包方式使用页面没有渲染成功的问题
  • gesp(三级)(14)洛谷:B4039:[GESP202409 三级] 回文拼接