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

本文介绍了如何在前后端分离的项目中,当前端无法直接下载文件时,后端如何通过SpringBoot的Controller和Service层获取文件,处理文件流并将其传递给前端进行下载的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述

  各位小伙伴们大家好,欢迎来到这个小扎扎的专栏 总结 | 提效 | 拓展,在这个系列专栏中记录了博主在学习期间总结的大块知识点,以及日常工作中遇到的各种技术点 ┗|`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对象
  })
},
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

扎哇太枣糕

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值