Vue項目中遇到了大文件分片上傳的問題,之前用過webuploader,索性就把Vue2.0與webuploader結合起來使用,封裝了一個vue的上傳組件,使用起來也比較舒爽。
上傳就上傳吧,為什么搞得那么麻煩,用分片上傳?
分片與并發結合,將一個大文件分割成多塊,并發上傳,極大地提高大文件的上傳速度。
當網絡問題導致傳輸錯誤時,只需要重傳出錯分片,而不是整個文件。另外分片傳輸能夠更加實時的跟蹤上傳進度。
實現后的界面:
主要是兩個文件,封裝的上傳組件和具體的ui頁面,上傳組件代碼下面有列出來。這兩個頁面的代碼放到github上了:https://github.com/shady-xia/Blog/tree/master/vue-webuploader。
在項目中引入webuploader
- 先在系統中引入jquery(插件基于jq,坑爹啊!),如果你不知道放哪,那就放到
index.html
中。 - 在官網上下載
Uploader.swf
和webuploader.min.js
,可以放到項目靜態目錄static
下面;在index.html
中引入webuploader.min.js。
(無需單獨再引入webuploader.css
,因為沒有幾行css,我們可以復制到vue組件中。)
<script src="/static/lib/jquery-2.2.3.min.js"></script>
<script src="/static/lib/webuploader/webuploader.min.js"></script>
需要注意的點:
- 在vue組件中,通過
import './webuploader';
的方式引入webuploader,會報''caller', 'callee', and 'arguments' properties may not be accessed on strict mode ...'的錯, 這是因為你的babel使用了嚴格模式,而caller這些在嚴格模式下禁止使用。所以可以直接在index.html中引入webuploader.js,或者手動去解決babel中'use strict'的問題。
基于webuploader封裝Vue組件
封裝好的組件upload.vue如下,接口可以根據具體的業務進行擴展。
注意:功能和ui分離,此組建封裝好了基本的功能,沒有提供ui,ui在具體的頁面上去實現。
<template><div class="upload"></div>
</template>
<script>export default {name: 'vue-upload',props: {accept: {type: Object,default: null,},// 上傳地址url: {type: String,default: '',},// 上傳最大數量 默認為100fileNumLimit: {type: Number,default: 100,},// 大小限制 默認2MfileSingleSizeLimit: {type: Number,default: 2048000,},// 上傳時傳給后端的參數,一般為token,key等formData: {type: Object,default: null},// 生成formData中文件的key,下面只是個例子,具體哪種形式和后端商議keyGenerator: {type: Function,default(file) {const currentTime = new Date().getTime();const key = `${currentTime}.${file.name}`;return key;},},multiple: {type: Boolean,default: false,},// 上傳按鈕IDuploadButton: {type: String,default: '',},},data() {return {uploader: null};},mounted() {this.initWebUpload();},methods: {initWebUpload() {this.uploader = WebUploader.create({auto: true, // 選完文件后,是否自動上傳swf: '/static/lib/webuploader/Uploader.swf', // swf文件路徑server: this.url, // 文件接收服務端pick: {id: this.uploadButton, // 選擇文件的按鈕multiple: this.multiple, // 是否多文件上傳 默認falselabel: '',},accept: this.getAccept(this.accept), // 允許選擇文件格式。threads: 3,fileNumLimit: this.fileNumLimit, // 限制上傳個數//fileSingleSizeLimit: this.fileSingleSizeLimit, // 限制單個上傳圖片的大小formData: this.formData, // 上傳所需參數chunked: true, //分片上傳chunkSize: 2048000, //分片大小duplicate: true, // 重復上傳});// 當有文件被添加進隊列的時候,添加到頁面預覽this.uploader.on('fileQueued', (file) => {this.$emit('fileChange', file);});this.uploader.on('uploadStart', (file) => {// 在這里可以準備好formData的數據//this.uploader.options.formData.key = this.keyGenerator(file);});// 文件上傳過程中創建進度條實時顯示。this.uploader.on('uploadProgress', (file, percentage) => {this.$emit('progress', file, percentage);});this.uploader.on('uploadSuccess', (file, response) => {this.$emit('success', file, response);});this.uploader.on('uploadError', (file, reason) => {console.error(reason);this.$emit('uploadError', file, reason);});this.uploader.on('error', (type) => {let errorMessage = '';if (type === 'F_EXCEED_SIZE') {errorMessage = `文件大小不能超過${this.fileSingleSizeLimit / (1024 * 1000)}M`;} else if (type === 'Q_EXCEED_NUM_LIMIT') {errorMessage = '文件上傳已達到最大上限數';} else {errorMessage = `上傳出錯!請檢查后重新上傳!錯誤代碼${type}`;}console.error(errorMessage);this.$emit('error', errorMessage);});this.uploader.on('uploadComplete', (file, response) => {this.$emit('complete', file, response);});},upload(file) {this.uploader.upload(file);},stop(file) {this.uploader.stop(file);},// 取消并中斷文件上傳cancelFile(file) {this.uploader.cancelFile(file);},// 在隊列中移除文件removeFile(file, bool) {this.uploader.removeFile(file, bool);},getAccept(accept) {switch (accept) {case 'text':return {title: 'Texts',exteensions: 'doc,docx,xls,xlsx,ppt,pptx,pdf,txt',mimeTypes: '.doc,docx,.xls,.xlsx,.ppt,.pptx,.pdf,.txt'};break;case 'video':return {title: 'Videos',exteensions: 'mp4',mimeTypes: '.mp4'};break;case 'image':return {title: 'Images',exteensions: 'gif,jpg,jpeg,bmp,png',mimeTypes: '.gif,.jpg,.jpeg,.bmp,.png'};break;default: return accept}},},};
</script>
<style lang="scss">
// 直接把官方的css粘過來就行了
</style>
使用封裝好的上傳組件
新建頁面,使用例子如下:
ui需要自己去實現。大概的代碼可以點這里。
<vue-uploadref="uploader"url="xxxxxx"uploadButton="#filePicker"multiple@fileChange="fileChange"@progress="onProgress"@success="onSuccess"
></vue-upload>
分片的原理及流程
當我們上傳一個大文件時,會被插件分片,ajax請求如下:
- 多個upload請求均為分片的請求,把大文件分成多個小份一次一次向服務器傳遞
- 分片完成后,即upload完成后,需要向服務器傳遞一個merge請求,讓服務器將多個分片文件合成一個文件
分片
可以看到發起了多次upload
的請求,我們來看看upload
發送的具體參數:
第一個配置(
content-disposition
)中的guid
和第二個配置中的access_token
,是我們通過webuploader配置里的formData
,即傳遞給服務器的參數
后面幾個配置是文件內容,id、name、type、size等
其中chunks
為總分片數,chunk
為當前第幾個分片。圖片中分別為12和9。當你看到chunk是11的upload請求時,代表這是最后一個upload請求了。
合并
分片后,文件還未整合,數據大概是下面這個樣子:
做完了分片后,其實工作還沒完,我們還要再發送個ajax請求給服務器,告訴他把我們上傳的幾個分片合并成一個完整的文件。
我怎么知道分片上傳完了,我在何時做合并?
webuploader插件有一個事件是uploadSuccess
,包含兩個參數,file
和后臺返回的response
;當所有分片上傳完畢,該事件會被觸發,
我們可以通過服務器返回的字段來判斷是否要做合并了。
比如后臺返回了needMerge
,我們看到它是true
的時候,就可以發送合并的請求了。
存在的已知問題
在做單文件暫停與繼續上傳時,發現了這個插件的bug:
1、當設置的threads>1
,使用單文件上傳功能,即stop方法傳入file時,會報錯Uncaught TypeError: Cannot read property 'file' of undefined
出錯的源碼如下:這是因為暫停時為了讓下一個文件繼續傳輸,會將當前的pool池中pop掉暫停的文件流。這里做了循環,最后一次循環的時候,v是undefined的。
2、設置的threads為1,能正常暫停,但是暫停后再繼續上傳是失敗的。
原理和上一個一樣,暫停時把當前文件流在pool
中全部pop
了,當文件開始upload
的時候,會檢查當期pool
,而此時已經沒有之前暫停的文件流了。
如果是針對所有文件整體的暫停和繼續,功能是正常的。
如果想實現單文件的暫停和繼續功能,需要修改源碼(我改了下源碼,發現耦合度較高,工程量比想象的大,遂放棄)