從設計到實現前端Uploader基礎類

前言

本文將帶你基於ES6的面向對象,脫離框架使用原生JS,從設計到代碼實現一個Uploader基礎類,再到實際投入使用。經過本文,你能夠了解到通常狀況下根據需求是如何合理構造出一個工具類lib。javascript

需求描述

相信不少人都用過/寫過上傳的邏輯,無非就是建立input[type=file]標籤,監聽onchange事件,添加到FormData發起請求。html

可是,想引入開源的工具時以爲增長了許多體積且定製性不知足,每次寫上傳邏輯又會寫不少冗餘性代碼。在不一樣的toC業務上,還要從新編寫本身的上傳組件樣式。vue

此時編寫一個Uploader基礎類,供於業務組件二次封裝,就顯得頗有必要。java

下面咱們來分析下使用場景與功能:node

  • 選擇文件後可根據配置,自動/手動上傳,定製化傳參數據,接收返回。
  • 可對選擇的文件進行控制,如:文件個數,格式不符,超出大小限制等等。
  • 操做已有文件,如:二次添加、失敗重傳、刪除等等。
  • 提供上傳狀態反饋,如:上傳中的進度、上傳成功/失敗。
  • 可用於拓展更多功能,如:拖拽上傳、圖片預覽、大文件分片等。

而後,咱們能夠根據需求,大概設計出想要的API效果,再根據API推導出內部實現。git

可經過配置實例化

const uploader = new Uploader({
  url: '',
  // 用於自動添加input標籤的容器
  wrapper: null,
  
  // 配置化的功能,多選、接受文件類型、自動上傳等等
  multiple: true,
  accept: '*',
  limit: -1, // 文件個數
  autoUpload: false
  
  // xhr配置
  header: {}, // 適用於JWT校驗
  data: {} // 添加額外參數
  withCredentials: false
});
複製代碼

狀態/事件監聽

// 鏈式調用更優雅
uploader
  .on('choose', files => {
    // 用於接受選擇的文件,根據業務規則過濾
  })
  .on('change', files => {
    // 添加、刪除文件時的觸發鉤子,用於更新視圖
    // 發起請求後狀態改變也會觸發
  })
  .on('progress', e => {
    // 回傳上傳進度
  })
  .on('success', ret => {/*...*/})
  .on('error', ret => {/*...*/})
複製代碼

外部調用方法

這裏主要暴露一些可能經過交互才觸發的功能,如選擇文件、手動上傳等github

uploader.chooseFile();

// 獨立出添加文件函數,方便拓展
// 可傳入slice大文件後的數組、拖拽添加文件
uploader.loadFiles(files);

// 相關操做
uploader.removeFile(file);
uploader.clearFiles()

// 凡是涉及到動態添加dom,事件綁定
// 應該提供銷燬API
uploader.destroy();
複製代碼

至此,能夠大概設計完咱們想要的uploader的大體效果,接着根據API進行內部實現。ajax

內部實現

使用ES6的class構建uploader類,把功能進行內部方法拆分,使用下劃線開頭標識內部方法。chrome

而後能夠給出如下大概的內部接口:數組

class Uploader {
  // 構造器,new的時候,合併默認配置
  constructor (option = {}) {}
  // 根據配置初始化,綁定事件
  _init () {}
  
  // 綁定鉤子與觸發
  on (evt) {}
  _callHook (evt) {}
  
  // 交互方法
  chooseFile () {}
  loadFiles (files) {}
  removeFile (file) {}
  clear () {}
  
  // 上傳處理
  upload (file) {}
  // 核心ajax發起請求
  _post (file) {}
}
複製代碼

構造器 - constructor

代碼比較簡單,這裏目標主要是定義默認參數,進行參數合併,而後調用初始化函數

class Uploader {
  constructor (option = {}) {
    const defaultOption = {
      url: '',
      // 若無聲明wrapper, 默認爲body元素
      wrapper: document.body,
      multiple: false,
      limit: -1,
      autoUpload: true,
      accept: '*',

      headers: {},
      data: {},
      withCredentials: false
    }
    this.setting = Object.assign(defaultOption, option)
    this._init()
  }
}
複製代碼

初始化 - _init

這裏初始化作了幾件事:維護一個內部文件數組uploadFiles,構建input標籤,綁定input標籤的事件,掛載dom。

爲何須要用一個數組去維護文件,由於從需求上看,咱們的每一個文件須要一個狀態去追蹤,因此咱們選擇內部維護一個數組,而不是直接將文件對象交給上層邏輯。

因爲邏輯比較混雜,分多了一個函數_initInputElement進行初始化input的屬性。

class Uploader {
  // ...
  
  _init () {
    this.uploadFiles = [];
    this.input = this._initInputElement(this.setting);
    // input的onchange事件處理函數
    this.changeHandler = e => {
      // ...
    };
    this.input.addEventListener('change', this.changeHandler);
    this.setting.wrapper.appendChild(this.input);
  }

  _initInputElement (setting) {
    const el = document.createElement('input');
    Object.entries({
      type: 'file',
      accept: setting.accept,
      multiple: setting.multiple,
      hidden: true
    }).forEach(([key, value]) => {
      el[key] = value;
    })''
    return el;
  }
}
複製代碼

看完上面的實現,有兩點須要說明一下:

  1. 爲了考慮到destroy()的實現,咱們須要在this屬性上暫存input標籤與綁定的事件。後續方便直接取來,解綁事件與去除dom。
  2. 其實把input事件函數changeHandler單獨抽離出去也能夠,更方便維護。可是會有this指向問題,由於handler裏咱們但願將this指向自己實例,若抽離出去就須要使用bind綁定一下當前上下文。

上文中的changeHanler,來單獨分析實現,這裏咱們要讀取文件,響應實例choose事件,將文件列表做爲參數傳遞給loadFiles

爲了更加貼合業務需求,能夠經過事件返回結果來判斷是中斷,仍是進入下一流程。

this.changeHandler = e => {
  const files = e.target.files;
  const ret = this._callHook('choose', files);
  if (ret !== false) {
    this.loadFiles(ret || e.target.files);
  }
};
複製代碼

經過這樣的實現,若是顯式返回false,咱們則不響應下一流程,不然拿返回結果||文件列表。這樣咱們就將判斷格式不符,超出大小限制等等這樣的邏輯交給上層實現,響應樣式控制。如如下例子:

uploader.on('choose', files => {
  const overSize = [].some.call(files, item => item.size > 1024 * 1024 * 10)
  if (overSize) {
    setTips('有文件超出大小限制')
    return false;
  }
  return files;
});
複製代碼

狀態事件綁定與響應

簡單實現上文提到的_callHook,將事件掛載在實例屬性上。由於要涉及到單個choose事件結果控制。沒有按照標準的發佈/訂閱模式的事件中心來作,有興趣的同窗能夠看看tiny-emitter的實現。

class Uploader {
  // ...
  on (evt, cb) {
    if (evt && typeof cb === 'function') {
      this['on' + evt] = cb;
    }
    return this;
  }

  _callHook (evt, ...args) {
    if (evt && this['on' + evt]) {
      return this['on' + evt].apply(this, args);
    }
    return;
  }
}
複製代碼

裝載文件列表 - loadFiles

傳進來文件列表參數,判斷個數響應事件,其次就是要封裝出內部列表的數據格式,方便追蹤狀態和對應對象,這裏咱們要用一個外部變量生成id,再根據autoUpload參數選擇是否自動上傳。

let uid = 1

class Uploader {
  // ...
  loadFiles (files) {
    if (!files) return false;

    if (this.limit !== -1 && 
        files.length && 
        files.length + this.uploadFiles.length > this.limit
    ) {
      this._callHook('exceed', files);
      return false;
    }
    // 構建約定的數據格式
    this.uploadFiles = this.uploadFiles.concat([].map.call(files, file => {
      return {
        uid: uid++,
        rawFile: file,
        fileName: file.name,
        size: file.size,
        status: 'ready'
      }
    }))

    this._callHook('change', this.uploadFiles);
    this.setting.autoUpload && this.upload()

    return true
  }
}
複製代碼

到這裏其實還沒完善,由於loadFiles能夠用於別的場景下添加文件,咱們再增長些許類型判斷代碼。

class Uploader {
  // ...
  loadFiles (files) {
    if (!files) return false;
    
+ const type = Object.prototype.toString.call(files)
+ if (type === '[object FileList]') {
+ files = [].slice.call(files)
+ } else if (type === '[object Object]' || type === '[object File]') {
+ files = [files]
+ }

    if (this.limit !== -1 && 
        files.length && 
        files.length + this.uploadFiles.length > this.limit
       ) {
      this._callHook('exceed', files);
      return false;
    }

+ this.uploadFiles = this.uploadFiles.concat(files.map(file => {
+ if (file.uid && file.rawFile) {
+ return file
+ } else {
        return {
          uid: uid++,
          rawFile: file,
          fileName: file.name,
          size: file.size,
          status: 'ready'
        }
      }
    }))

    this._callHook('change', this.uploadFiles);
    this.setting.autoUpload && this.upload()

    return true
  }
}
複製代碼

上傳文件列表 - upload

這裏可根據傳進來的參數,判斷是上傳當前列表,仍是單獨重傳一個,建議是每個文件單獨走一次接口(有助於失敗時的文件追蹤)。

upload (file) {
  if (!this.uploadFiles.length && !file) return;

  if (file) {
    const target = this.uploadFiles.find(
      item => item.uid === file.uid || item.uid === file
    )
    target && target.status !== 'success' && this._post(target)
  } else {
    this.uploadFiles.forEach(file => {
      file.status === 'ready' && this._post(file)
    })
  }
}
複製代碼

當中涉及到的_post函數,咱們往下再單獨實現。

交互方法

這裏都是些供給外部操做的方法,實現比較簡單就直接上代碼了。

class Uploader {
  // ...
  chooseFile () {
    // 每次都須要清空value,不然同一文件不觸發change
    this.input.value = ''
    this.input.click()
  }
  
  removeFile (file) {
    const id = file.id || file
    const index = this.uploadFiles.findIndex(item => item.id === id)
    if (index > -1) {
      this.uploadFiles.splice(index, 1)
      this._callHook('change', this.uploadFiles);
    }
  }

  clear () {
    this.uploadFiles = []
    this._callHook('change', this.uploadFiles);
  }
  
  destroy () {
    this.input.removeEventHandler('change', this.changeHandler)
    this.setting.wrapper.removeChild(this.input)
  }
  // ...
}
複製代碼

有一點要注意的是,主動調用chooseFile,須要在用戶交互之下才會觸發選擇文件框,就是說要在某個按鈕點擊事件回調裏,進行調用chooseFile。不然會出現如下這樣的提示:

寫到這裏,咱們能夠根據已有代碼嘗試一下,打印upload時的內部uploadList,結果正確。

發起請求 - _post

這個是比較關鍵的函數,咱們用原生XHR實現,由於fetch並不支持progress事件。簡單描述下要作的事:

  1. 構建FormData,將文件與配置中的data進行添加。
  2. 構建xhr,設置配置中的header、withCredentials,配置相關事件
  • onload事件:處理響應的狀態,返回數據並改寫文件列表中的狀態,響應外部change等相關狀態事件。
  • onerror事件:處理錯誤狀態,改寫文件列表,拋出錯誤,響應外部error事件
  • onprogress事件:根據返回的事件,計算好百分比,響應外部onprogress事件
  1. 由於xhr的返回格式不太友好,咱們須要額外編寫兩個函數處理http響應:parseSuccessparseError
_post (file) {
  if (!file.rawFile) return

  const { headers, data, withCredentials } = this.setting
  const xhr = new XMLHttpRequest()
  const formData = new FormData()
  formData.append('file', file.rawFile, file.fileName)

  Object.keys(data).forEach(key => {
    formData.append(key, data[key])
  })
  Object.keys(headers).forEach(key => {
    xhr.setRequestHeader(key, headers[key])
  })

  file.status = 'uploading'

  xhr.withCredentials = !!withCredentials
  xhr.onload = () => {
    /* 處理響應 */
    if (xhr.status < 200 || xhr.status >= 300) {
      file.status = 'error'
      this._callHook('error', parseError(xhr), file, this.uploadFiles)
    } else {
      file.status = 'success'
      this._callHook('success', parseSuccess(xhr), file, this.uploadFiles)
    }
  }
 
  xhr.onerror = e => {
    /* 處理失敗 */
    file.status = 'error'
    this._callHook('error', parseError(xhr), file, this.uploadFiles)
  }
 
  xhr.upload.onprogress = e => {
    /* 處理上傳進度 */
    const { total, loaded } = e
    e.percent = total > 0 ? loaded / total * 100 : 0
    this._callHook('progress', e, file, this.uploadFiles)
  }

  xhr.open('post', this.setting.url, true)
  xhr.send(formData)
}
複製代碼
parseSuccess

將響應體嘗試JSON反序列化,失敗的話再返回原樣文本

const parseSuccess = xhr => {
  let response = xhr.responseText
  if (response) {
    try {
      return JSON.parse(response)
    } catch (error) {}
  }
  return response
}
複製代碼
parseError

一樣的,JSON反序列化,此處還要拋出個錯誤,記錄錯誤信息。

const parseError = xhr => {
  let msg = ''
  let { responseText, responseType, status, statusText } = xhr
  if (!responseText && responseType === 'text') {
    try {
      msg = JSON.parse(responseText)
    } catch (error) {
      msg = responseText
    }
  } else {
    msg = `${status} ${statusText}`
  }

  const err = new Error(msg)
  err.status = status
  return err
}
複製代碼

至此,一個完整的Upload類已經構造完成,整合下來大概200行代碼多點,因爲篇幅問題,完整的代碼已放在我的github裏。

測試與實踐

寫好一個類,固然是上手實踐一下,因爲測試代碼並非本文關鍵,因此採用截圖的方式呈現。爲了呈現良好的效果,把chrome裏的network調成自定義降速,並在測試失敗重傳時,關閉網絡。

服務端

這裏用node搭建了一個小的http服務器,用multiparty處理文件接收。

客戶端

簡單的用html結合vue實現了一下,會發現將業務代碼跟基礎代碼分開實現後,簡潔明瞭很多

拓展拖拽上傳

拖拽上傳注意兩個事情就是

  1. 監聽drop事件,獲取e.dataTransfer.files
  2. 監聽dragover事件,並執行preventDefault(),防止瀏覽器彈窗。
更改客戶端代碼以下:

效果圖GIF

優化與總結

本文涉及的所有源代碼以及測試代碼均已上傳到github倉庫中,有興趣的同窗可自行查閱。

代碼當中還存在很多須要的優化項以及爭論項,等待各位讀者去斟酌改良:

  • 文件大小判斷是否應該結合到類裏面?看需求,由於有時候可能會有根據.zip壓縮包的文件,能夠容許更大的體積。
  • 是否應該提供可重寫ajax函數的配置項?
  • 參數是否應該可傳入一個函數動態肯定?
  • ...
相關文章
相關標籤/搜索