經過ES6 封裝了一個上傳文件的方法 XMLHttpRequest() 通用

### 上傳進度回顯,上傳速度回顯app

### 源碼以下,新建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)
    }
  }
}

使用方式post

      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
        }
      })

####this

####url

ENDspa

####prototype

####code

相關文章
相關標籤/搜索