后端接口返回文件流,前端下载(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对象
  })
},
相关推荐
gnip12 小时前
企业级配置式表单组件封装
前端·javascript·vue.js
一只叫煤球的猫13 小时前
写代码很6,面试秒变菜鸟?不卖课,面试官视角走心探讨
前端·后端·面试
excel14 小时前
Three.js 材质(Material)详解 —— 区别、原理、场景与示例
前端
掘金安东尼14 小时前
抛弃自定义模态框:原生Dialog的实力
前端·javascript·github
皮皮林55115 小时前
IDEA 源码阅读利器,你居然还不会?
java·intellij idea
hj5914_前端新手18 小时前
javascript基础- 函数中 this 指向、call、apply、bind
前端·javascript
薛定谔的算法18 小时前
低代码编辑器项目设计与实现:以JSON为核心的数据驱动架构
前端·react.js·前端框架
Hilaku18 小时前
都2025年了,我们还有必要为了兼容性,去写那么多polyfill吗?
前端·javascript·css
yangcode18 小时前
iOS 苹果内购 Storekit 2
前端
LuckySusu18 小时前
【js篇】JavaScript 原型修改 vs 重写:深入理解 constructor的指向问题
前端·javascript