通过ES6 封装了一个上传文件的方法 XMLHttpRequest() 通用

### 上传进度回显,上传速度回显

### 源码如下,新建index.js装起来

export class UploadServers {
  constructor (options) {
    this.xhr = null
    this.startTime = null
    this.startFileSize = 0
    this.formData = null
    // this = options
    Object.keys(options).map(item => {
      this[item] = options[item]
    })
    this.init(options)
  }
  init (options) {
    this.config = {...this.config, ...options}
    this.xhr = new XMLHttpRequest()
    this.formData = new FormData()
    if (this.config.data && Object.prototype.toString.call(this.config.data) === '[object Object]') {
      // 循环添加其他参数
      this.config.data.keys(item => {
        this.formData.append(item, this.config.data[item])
      })
    }
    // console.log(this.config)
    // console.log(this.config.file.toString())
    // console.log(Array.prototype.slice.call(this.config.file).toString())
    if (this.config.file.toString() === '[object FileList]' || this.config.file.toString() === '[object File]' || this.config.file.toString() === '[object Array]' || this.config.file.toString().includes('[object File]')) {
      this.uploadFile(this.config.file, true)
    } else {
      this.uploadFile(this.config.file)
    }
  }
  uploadFile (file, isArray) {
    // this.xhr
    const _this = this
    if (isArray) {
      Object.values(file).forEach(function (item) {
        _this.formData.append(_this.config.uploadFileName, item)
      })
    } else {
      this.formData.append(this.config.uploadFileName, file)
    }
    this.xhr.open('post', this.config.url, true)
    this.xhr.onload = function (e) {
      _this.updataSucess(e)
    }
    this.xhr.onerror = function (e) {
      _this.updataError(e)
    }
    this.xhr.upload.onprogress = function (e) {
      _this.progressChange(e)
    }
    this.xhr.upload.onloadstart = function (e) {
      _this.startUpload(e)
    }
    this.xhr.send(this.formData)
  }
  startUpload (e) {
    // console.log(e)
    this.startTime = new Date().getTime()
    this.startFileSize = 0
  }
  updataSucess (e) {
    // console.log(e)
    // console.log(this)
    // console.log(uploadServers)
    this.config.success(e)
  }
  updataError (e) {
    console.log(e)
    this.config.error(e)
  }
  progressChange (e) {
    // console.log(e)
    if (e.lengthComputable) {
      const newTime = new Date().getTime()
      let pertime = (newTime - this.startTime) / 1000
      // 如果时间为0 则返回避免出现Infinity 兼容IOS进度函数读取过快问题
      if (pertime === 0) pertime = 0.001
      this.startTime = newTime

      const perload = e.loaded - this.startFileSize
      const lave = e.loaded / e.total
      this.startFileSize = e.loaded

      let speed = perload / pertime
      // console.log(perload, pertime)
      // const speeds = speed

      let units = 'b/s'
      if (speed / 1024 > 1) {
        speed = speed / 1024
        units = 'k/s'
      }
      if (speed / 1024 > 1) {
        speed = speed / 1024
        units = 'M/s'
      }
      if (speed / 1024 > 1) {
        speed = speed / 1024
        units = 'G/s'
      }
      // console.log(speed)
      speed = speed.toFixed(1)
      // console.log(speed)
      // const resout = ((e.total - e.loaded) / speeds).toFixed(1)

      this.config.progress(e, speed, lave, e.loaded, units)
    }
  }
}

使用方式

      let initUploadFileChange = new UploadServers({
        url: _this.url,
        data: _this.data,
        file: fileList || null,
        fileClassName: null,
        uploadFileName: _this.fileOption || 'multipartFiles',
        progress: function (e, speed, lave, loaded, units) {
          // console.log(e, speed, lave, loaded, units)
          _this.percentage = parseInt(lave * 100)
        },
        success: function (e) {
          if (e.target.status === 200 && e.target.response) {
            const parseJson = JSON.parse(e.target.response)
          }
          // 设置状态为未上传状态
          _this.processStatus = false
        },
        error: function (e) {
          // 上传失败 应将文件通过File流读取出来进行回显 并展示给用户提示上传失败 请重新上传 或者自动重新上传
          _this.processStatus = false
        }
      })

####

####

END

####

####

转载于:https://www.cnblogs.com/fang-li/p/11242908.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值