大文件分片上傳
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: ‘‘,
},
// 上傳最大數量 默認為100
fileNumLimit: {
type: Number,
default: 100,
},
// 大小限制 默認2M
fileSingleSizeLimit: {
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,
},
// 上傳按鈕ID
uploadButton: {
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, // 是否多文件上傳 默認false
label: ‘‘,
},
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-upload
ref="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
,而此時已經沒有之前暫停的文件流了。
大文件分片上傳