js文件下载 - 戴向天

51 篇文章 0 订阅

大家好!我叫戴向天

QQ群:602504799


/**
 * Author: 戴向天
 * 文件下载
 * 使用方法
 * const server = new DownloadServer({
 *   baseUrl: ''
 * })
 * server.run('get', url).then(res => {
 *  downloadByURL(res.url, fileName) // 直接下载
 * })
 * @return {Promise}
 */
export default class downloadServer {
  constructor (config) {
    this.baseUrl = config.baseUrl || ''
    this.headers = config.headers || {}
    return this
  }
  run (type, url, params, headers = {}, onprogress) {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest()
      xhr.responseType = 'blob'
      xhr.open(type, this.baseUrl + url, true)
      headers = {
        ...this.headers,
        ...headers
      }
      for (const key in headers) {
        xhr.setRequestHeader(key, headers[key])
      }
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4 && xhr.status === 200) {
          const resultType = xhr.response.type
          if (resultType === 'application/json') {
            var reader = new FileReader()
            reader.onload = function (event) {
              var content = reader.result
              resolve(JSON.parse(content))
            }
            return reader.readAsText(xhr.response)
          }
          const response = xhr.getAllResponseHeaders().trim().split(/[\r\n]+/)
          const headerMap = {}
          response.forEach(function (line) {
            const parts = line.split(': ')
            const header = parts.shift()
            const value = parts.join(': ')
            headerMap[header] = value
          })
          const fileName = decodeURI(headerMap['content-disposition']).split('=').pop()
          const fileType = fileName.split('.')[1]
          let type // 产生二进制blob的MIME类型
          switch (fileType) {
          case 'xls' || 'xlsx':
            // 为excel文件
            type = 'application/vnd.ms-excel'
            break
          case 'doc':
            type = 'application/msword'
            break
          case 'docx':
            type =
              'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
            break
          case 'pdf':
            type = 'application/pdf'
            break
          case 'bmp':
            type = 'image/bmp'
            break
          case 'png':
            type = 'image/png'
            break
          case 'gif':
            type = 'image/gif'
            break
          case 'jpe' || 'jpeg' || 'jpg':
            type = 'image/jpeg'
            break
          }
          const blobStream = new Blob([xhr.response], { type })
          const url = window.URL.createObjectURL(blobStream)
          resolve({ url, fileName })
        }
      }
      if (onprogress) {
        xhr.onprogress = onprogress
      }
      xhr.onerror = (event) => {
        reject(event)
      }
      const isForm = Object.prototype.toString.call(params).toLowerCase().indexOf('formdata') >= 0
      xhr.send(isForm ? params : typeof params === 'string' ? params : JSON.stringify(params))
    })
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值