前端处理下载预览

1.若后端直接返回链接地址,可以直接进行预览或者下载,配置响应头,如下:

Content-Disposition:这个响应头可以决定内容是 预览 还是 下载

它支持三种格式的值:

  1. Content-Disposition: inline
    此时,消息体会以页面的一部分或者整个页面的形式展示。(预览)
  2. Content-Disposition: attachment
    消息体应该被下载,默认文件名和 url 格式有关。
  3. Content-Disposition: attachment; filename="filename.jpg"
    消息体应该被下载,默认文件名可指定。

注:如果需要预览,需要配合适当的 Content-Type 食用;

实例:

const user = {
  name: "嘻嘻嘻",
  blogUrl: "https://juejin.cn/user/1714893870865303"
}

const contentDispositionInline = async (req, res, next) => {
  res.setHeader('Content-Disposition', 'inline')
  res.send(user)
}

const contentDispositionFilename = async (req, res, next) => {
  res.setHeader('Content-Disposition', 'attachment; filename="chunge.json"')
  res.send(user)
}

const contentDispositionNoFilename = async (req, res, next) => {
  res.setHeader('Content-Disposition', 'attachment')
  res.send(user)
}

参考链接:用头👴解决!前端必知必会的几个实用响应头 - 掘金

2.base64转化为blob  后进行下载(需要后端的配合)

// 附件下载  这里的的data就是content数据
const downloadAttach = (id) => {
  downloadAttachment({ attachmentId: id })
    .then(({ data }) => {
      const raw = window.atob(data.content);//解码base64
      const rawLength = raw.length;
      const uInt8Array = new Uint8Array(rawLength); 
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i); //转换为 Uint8
      }
      const blob = new Blob([uInt8Array], { type: data.contentType });
 
      // 下载方法
      const elink = document.createElement("a");
      elink.download = data.attachName;
      elink.style.display = "none";
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
 
      // 预览方法
      window.open(URL.createObjectURL(blob))

    })
    .catch(() => {});
};

3.利用插件file-svaer

 /**
   * @description 文件下载
   * @param  { string } path 地址
   * @param  { string } name 名称
   */

import FileSaver from "file-saver"
​​​​​​​ fileSave(path, name) {
    FileSaver.saveAs(path, name)
  },

//若返回的是blob流
let blob = new Blob([path], { type })
fileSave(blob,name)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值