• 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)
    }
  • 相关阅读:
    subsonic资源聚合
    一些经典的框架
    小毛看传统图书行业
    商界传媒20092010 从容就业,激情创业(企业家走进北在)活动记
    Beijing Perl Workshop 2009
    智力更生小毛笔记&心得
    使用world 2007 或是windows live writer写blog的设置
    php技术准备
    我需要知道的技术常识
    重新分配ip
  • 原文地址:https://www.cnblogs.com/llcdbk/p/16531705.html
Copyright © 2020-2023  润新知