a标签下载视频,批量下载

602 阅读1分钟

1.a标签下载视频方式(解决直接打开视频、图片等文件的问题,在控制台能够看到blob下载转码过程)

const xhr = new XMLHttpRequest()
xhr.open('GET', '/upload/user.png', true)
xhr.responseType = 'blob'
xhr.onload = function() {
  if (this.status === 200) {
  const fileName = 'test.jpg'
    const blob = new Blob([this.response])
    const blobUrl = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = blobUrl
    a.download = fileName
    a.click()
    window.URL.revokeObjectURL(blobUrl)
  }
};
xhr.send()

2.后端做下载,提供路径(后端做好下载接口直接赋值给a标签,注意要携带后端提供的地址: href=源+接口地址+文件路径)

  console.log(path)
  const url = 'http://ip地址/iot/file/fileDownload?filePath='
  const fileName = path.slice(path.lastIndexOf('/') + 1)
  const a = document.createElement('a')
  a.download = fileName
  a.href = url + path
  a.click()
  a.remove()
   }

3.第二种为单个文件下载,在批量下载中可以同步调用函数即可。这里批量下载提供一种方式

const triggerDelay = 100
const removeDelay = 1000
const ExportFn1 = function (arr) {
  arr.forEach((url, index) => {
    const path = 'http:/xxx/iot/file/fileDownload?filePath='
    createIFrame(path + url, index * triggerDelay, removeDelay)
  })

  // 这里是创建iframe的方法
  function createIFrame(url, triggerDelay, removeDelay) {
    // 动态添加iframe,设置src,然后删除
    setTimeout(function () {
      const frame = document.createElement('iframe')
      frame.src = url
      frame.style.display = 'none'
      document.body.appendChild(frame)
      setTimeout(function () {
        frame.remove()
      }, removeDelay)
    }, triggerDelay)
  }
}