文件下载、上传和断点续传数据处理的公共基本方法

import axios from './axios'

export const requestBaseUpload = (url, params, type = 'post', headers = { 'Content-Type': 'multipart/form-data' }, options = {}, loading = true) => {
  const data = new FormData()
  const keys = Object.keys(params)
  keys.forEach(key => data.append(key, params[key]))
  options.headers = Object.assign(headers, options.headers)
  return axios[type](url, data, options, loading)
}

/**
 * 谷歌 火狐 IE10+
 * 小版本或者老版本没有测试
 */
export const requestBaseDownload = (url, params, fileName = '', type = 'get', options = { responseType: 'blob' }, loading = true) => {
  return axios[type](url, params, options, loading).then(data => {
    if (!data || !data.data) {
      return
    }
    // 根据请求获取文件名
    if (!fileName) {
      const re = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/i
      const disposition = data.headers['content-disposition']
      const match = disposition && disposition.match(re)
      if (match) {
        fileName = match[1]
      }
    }

    if (navigator.msSaveBlob) {
      // 兼容 IE
      navigator.msSaveBlob(new Blob([data]), fileName)
      return
    }

    // 使用 a[download] 方式下载
    const url = window.URL.createObjectURL(new Blob([data.data]))
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', fileName)
    document.body.appendChild(link)

    // 兼容不支持 link.click()
    const evt = new MouseEvent('click')
    link.dispatchEvent(evt)

    // 兼容不支持 link.remove()
    document.body.removeChild(link)
  })
}

// 断点上传,数据处理
// cb 用来接收处理好的分片数据
export const requestBaseSpliceUpload = (file, size = 1024 * 1024, cb = () => {}) => {
  var reader = new FileReader()
  reader.readAsArrayBuffer(file)
  reader.addEventListener('load', () => {
    const data = []
    const [name, ext] = file.name.split('.')
    for (let i = 0, len = this.result.byteLength; i < len; i += size) {
      data.push(this.result.slice(i, i + size))
    }
    cb({ name, ext, data })
  })
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值