常用工具函数 (下载篇)

254 阅读1分钟

下载Excel,文件等

接口返回流文件

export function getLoadTable(query) {
    return baseRequest({
        url:'/catalog/dataOpen/dataExport',

        method: 'GET',

        params: query,

        responseType: 'blob' // **这个字段必须加**
    })
}

接受到后端的文件流就可以下载了

export function convertRes2Blob(response) {
    // 提取文件名

    const filename = response.headers['content-disposition'].match(

      /filename=(.*)/

    )[1]

    // 将二进制流转为blob 

    const blob = new Blob([response.data], { type: 'application/octet-stream' })

    if (typeof window.navigator.msSaveBlob !== 'undefined') {
      // 兼容IE,window.navigator.msSaveBlob:以本地方式保存文件

      window.navigator.msSaveBlob(blob, decodeURI(filename))

    } else {
      // 创建新的URL并指向File对象或者Blob对象的地址

      const blobURL = window.URL.createObjectURL(blob)

      // 创建a标签,用于跳转至下载链接

      const tempLink = document.createElement('a')

      tempLink.style.display = 'none'

      tempLink.href = blobURL

      tempLink.setAttribute('download', decodeURI(filename))

      // 兼容:某些浏览器不支持HTML5的download属性

      if (typeof tempLink.download === 'undefined') {
        tempLink.setAttribute('target', '_blank')
      }
      // 挂载a标签

      document.body.appendChild(tempLink)

      tempLink.click()

      document.body.removeChild(tempLink)

      // 释放blob URL地址

      window.URL.revokeObjectURL(blobURL)

    }

  }

# 在后端没有定义数据的格式的情况下附件下载

filesLoad(item) {
console.log(item)
attachDownload({ id: item.id }).then((res) => {
console.log(res)
if (res) {
let blob = new Blob([res.data], { type: ‘application/vnd.ms-excel;charset=utf-8’ })
if (window.navigator.msSaveBlob) {
window, navigator.msSaveBlob(blob, item.name)
} else {
let url = window.URL.createObjectURL(blob)
let link = document.createElement(‘a’)
link.style.display = ‘none’
link.href = url
link.download = item.name
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
} else {
this.$message.error(‘下载失败!’)
}
})
}

HLS拉视频流

//hls的引用
  //方式一
 <script type="text/javascript" src="../../../static/HLS/hls.min.js"></script>
 //方式二
  npm install hls.js
  yarn add hls.js
  import Hls from 'hls.js'
 
 
<video id="videoElement1" controls  muted  preload="auto"  style="width:100%; fit:fill;"></video>

//拿到后端的url 传入refId= this.$refs.videoElement1
 showVideo(url, refId) {
            let video = refId; //定义挂载点
            console.log(video, "99999");
            this.hlsjs = new Hls();
            this.hlsjs.loadSource(url);
            this.hlsjs.attachMedia(video);
            this.hlsjs.on(Hls.Events.MANIFEST_PARSED, () => {
                video.play();
            });
            this.hlsjs.on(Hls.Events.ERROR, (event, data) => {
                console.log(event, data);
                // 监听出错事件
                console.log("加载失败");
            });
        },