Vue2.0結合webuploader實現檔案分區上傳功能,
Vue項目中遇到了大檔案分區上傳的問題,之前用過webuploader,索性就把Vue2.0與webuploader結合起來使用,封裝了一個vue的上傳組件,使用起來也比較舒爽。
上傳就上傳吧,為什麼搞得那麼麻煩,用分區上傳?
分區與並髮結合,將一個大檔案分割成多塊,並發上傳,極大地提高大檔案的上傳速度。
當網路問題導致傳輸錯誤時,只需要重傳出錯分區,而不是整個檔案。另外分區傳輸能夠更加即時的跟蹤上傳進度。
實現後的介面:
主要是兩個檔案,封裝的上傳組件和具體的ui頁面,上傳組件代碼下面有列出來。這兩個頁面的代碼放到github上了: https://github.com/shady-xia/Blog/tree/master/vue-webuploader 。
在項目中引入webuploader
1.先在系統中引入jquery(外掛程式基於jq,坑爹啊!),如果你不知道放哪,那就放到 index.html 中。
2.在 官網 上下載 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>
需要注意的點:
1.在vue組件中,通過 import './webuploader'
; 的方式引入webuploader
,會報''caller', 'callee', and 'arguments' properties may not be accessed on strict mode ...'的錯, 這是因為你的babel使用了strict 模式,而caller這些在strict 模式下禁止使用。所以 可以直接在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請求如下:
1.多個upload請求均為分區的請求,把大檔案分成多個小份一次一次向伺服器傳遞
2.分區完成後,即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 ,而此時已經沒有之前暫停檔案流了。
如果是針對所有檔案整體的暫停和繼續,功能是正常的。
總結
以上所述是小編給大家介紹的Vue2.0結合webuploader實現檔案分區上傳功能,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對幫客之家網站的支援!