通过blob对象下载文件

876 阅读1分钟

有时候公司或者我们自己想要通过文件流的形式下载文件,或者我们想将某些数据以某种文件格式下载下来。blob是个不错的选择。 基本上所有的文件都能生成。

定义一个类,封装blob
/**
 * 以blob对象的形式下载文件
 * @param { Array } arr 类型可以是:ArrayBuffer, ArrayBufferView, Blob, DOMString
 * @param { String } type 保存的文件类型 [css:'text/css', doc:'application/msword', docx:'application/vnd.openxmlformats-officedocument.wordprocessingml.document', gif:'image/gif', html:'text/html', jpg:'image/jpeg', js:'text/javascript', json:'application/json', mp3:'audio/mpeg', png:'image/png', pdf:'application/pdf', ppt:'application/vnd.ms-powerpoint', pptx:'application/vnd.openxmlformats-officedocument.presentationml.presentation', txt:'text/plain', zip:'application/zip']
 * @param { String } name 下载之后的文件名
 */
export class DownloadBlob {
  constructor({ arr = [], type = 'text/plain', name }) {
    if (arr instanceof Array) {
      this.blobData = arr
    } else {
      this.blobData = [arr]
    }
    this.fileName = name
    this.fileType = type
    this.blob = new Blob(this.blobData, { type: type })
  }
  download() {
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(this.blob, this.fileName)
    } else {
      let a = document.createElement('a')
      let href = window.URL.createObjectURL(this.blob) // 创建下载的链接
      a.href = href
      a.download = this.fileName // 下载后文件名
      document.body.appendChild(a)
      // downloadElement.click() // 点击下载
      let evt = document.createEvent('MouseEvents')
      evt.initEvent('click', false, false)
      a.dispatchEvent(evt)
      // window.URL.revokeObjectURL(href) // 释放掉blob对象
      document.body.removeChild(a)
    }
  }
}
使用
let download = new DownloadBlob({ arr: ['aabbcc'], type: 'text/plain', name: '测试' })
download.download()