首页 > 建站教程 > JS、jQ、TS >  blob流导出文件以及对应格式正文

blob流导出文件以及对应格式

下面的download是请求后端接口,返回的是二进制流,通过Blob转为blob对象,然后通过a链接的download属性,进行下载:
downloadFunc(filePath, filename) {
  const formData = new FormData()
  download({
    path: filePath
  }).then(response => {
    const blob = new Blob([response], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"})
    const fileName = filename
    if ('download' in document.createElement('a')) { // 非IE下载
      const elink = document.createElement('a')
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else { // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
  })
},
下面是上面转blob时,可能用到的格式:
后缀 MIME Type
.doc application/msword
.docx application/vnd.openxmlformats-officedocument.wordprocessingml.document
.xls application/vnd.ms-excel
.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.ppt application/vnd.ms-powerpoint
.pptx application/vnd.openxmlformats-officedocument.presentationml.presentation
.pdf application/pdf