js 文件下载功能

js 文件下载功能import { message } from 'antd' export function getBlob(url: string): Promise<any> { return new Promise(resolve => { const xhr = new X

js  文件下载功能

import { message } from ‘antd’

export function getBlob(url: string): Promise<any> {
  return new Promise(resolve => {
    const xhr = new XMLHttpRequest()
    xhr.open(‘GET’, url, true)
    xhr.setRequestHeader(‘Authorization’, window.localStorage.getItem(‘token’))
    xhr.responseType = ‘blob’
    message.loading(”, 0)
    xhr.onload = () => {
      message.destroy()
      if (xhr.status === 200) {
        if (xhr.response.type == ‘application/json’) {
          var reader = new FileReader()
          reader.addEventListener(‘loadend’, function (e) {
            let res = JSON.parse(e.target.result as any)
            if (res?.code != 200) {
              message.error(res.message)
            }
          })
          reader.readAsText(xhr.response)
          return
        }
        resolve({
          blob: xhr.response,
          fileName: getFileName(xhr),
        })
      }
    }
    xhr.send()
  })
}

function getFileName(xhr) {
  var filename = ”
  var disposition = xhr.getResponseHeader(‘Content-Disposition’)
  if (disposition && disposition.indexOf(‘attachment’) !== -1) {
    var filenameRegex = /filename[^;=\n]*=(([‘”]).*?\2|[^;\n]*)/
    var matches = filenameRegex.exec(disposition)
    if (matches != null && matches[1]) {
      filename = matches[1].replace(/[‘”]/g, ”)
    }
  }
  return filename
}

export function saveBlob(
  blob: Blob,
  blobFileName?: string,
  filename?: string
): void {
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  if (window.navigator.msSaveOrOpenBlob) {
    ;(window.navigator as any).msSaveBlob(blob, filename)
  } else {
    const link = document.createElement(‘a’)
    const body: HTMLBodyElement = document.querySelector(
      ‘body’
    ) as HTMLBodyElement
    link.href = window.URL.createObjectURL(blob)
    if (filename) {
      if (blobFileName) {
        link.download = filename + ‘.’ + blobFileName.split(‘.’).pop()
      }
    } else {
      link.download = blobFileName ? decodeURI(blobFileName) : null
    }
    link.style.display = ‘none’
    body.appendChild(link)
    link.click()
    body.removeChild(link)
    window.URL.revokeObjectURL(link.href)
  }
}

export const downloadFile = async (url: string, filename?: string) => {
  if (!url) return
  const blobFile = await getBlob(url)
  saveBlob(blobFile.blob, blobFile.fileName, filename)
}
(0)
编程小号编程小号
上一篇 2023-08-27 09:06
下一篇 2023-08-27

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注