Vue項(xiàng)目中遇到了大文件分片上傳的問題,之前用過webuploader,索性就把Vue2.0與webuploader結(jié)合起來使用,封裝了一個(gè)vue的上傳組件,使用起來也比較舒爽。
上傳就上傳吧,為什么搞得那么麻煩,用分片上傳?
分片與并發(fā)結(jié)合,將一個(gè)大文件分割成多塊,并發(fā)上傳,極大地提高大文件的上傳速度。
當(dāng)網(wǎng)絡(luò)問題導(dǎo)致傳輸錯(cuò)誤時(shí),只需要重傳出錯(cuò)分片,而不是整個(gè)文件。另外分片傳輸能夠更加實(shí)時(shí)的跟蹤上傳進(jìn)度。
實(shí)現(xiàn)后的界面:
 
主要是兩個(gè)文件,封裝的上傳組件和具體的ui頁面,上傳組件代碼下面有列出來。這兩個(gè)頁面的代碼放到github上了: https://github.com/shady-xia/Blog/tree/master/vue-webuploader 。
在項(xiàng)目中引入webuploader
1.先在系統(tǒng)中引入jquery(插件基于jq,坑爹啊!),如果你不知道放哪,那就放到 index.html 中。
2.在 官網(wǎng) 上下載 Uploader.swf 和 webuploader.min.js ,可以放到項(xiàng)目靜態(tài)目錄 static 下面;在 index.html 中引入webuploader.min.js。
(無需單獨(dú)再引入 webuploader.css ,因?yàn)闆]有幾行css,我們可以復(fù)制到vue組件中。)<script src="/static/lib/jquery-2.2.3.min.js"></script><script src="/static/lib/webuploader/webuploader.min.js"></script>
需要注意的點(diǎn):
1.在vue組件中,通過 import './webuploader'; 的方式引入webuploader,會(huì)報(bào)''caller', 'callee', and 'arguments' properties may not be accessed on strict mode ...'的錯(cuò), 這是因?yàn)槟愕腷abel使用了嚴(yán)格模式,而caller這些在嚴(yán)格模式下禁止使用。所以 可以直接在index.html中引入webuploader.js ,或者手動(dòng)去解決babel中'use strict'的問題。
基于webuploader封裝Vue組件
封裝好的組件upload.vue如下,接口可以根據(jù)具體的業(yè)務(wù)進(jìn)行擴(kuò)展。
注意:功能和ui分離,此組建封裝好了基本的功能,沒有提供ui,ui在具體的頁面上去實(shí)現(xiàn)。
<template> <div class="upload"> </div></template><script> export default {  name: 'vue-upload',  props: {   accept: {    type: Object,    default: null,   },   // 上傳地址   url: {    type: String,    default: '',   },   // 上傳最大數(shù)量 默認(rèn)為100   fileNumLimit: {    type: Number,    default: 100,   },   // 大小限制 默認(rèn)2M   fileSingleSizeLimit: {    type: Number,    default: 2048000,   },   // 上傳時(shí)傳給后端的參數(shù),一般為token,key等   formData: {    type: Object,    default: null   },   // 生成formData中文件的key,下面只是個(gè)例子,具體哪種形式和后端商議   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, // 選完文件后,是否自動(dòng)上傳     swf: '/static/lib/webuploader/Uploader.swf', // swf文件路徑     server: this.url, // 文件接收服務(wù)端     pick: {      id: this.uploadButton,  // 選擇文件的按鈕      multiple: this.multiple, // 是否多文件上傳 默認(rèn)false      label: '',     },     accept: this.getAccept(this.accept), // 允許選擇文件格式。     threads: 3,     fileNumLimit: this.fileNumLimit, // 限制上傳個(gè)數(shù)     //fileSingleSizeLimit: this.fileSingleSizeLimit, // 限制單個(gè)上傳圖片的大小     formData: this.formData, // 上傳所需參數(shù)     chunked: true,   //分片上傳     chunkSize: 2048000, //分片大小     duplicate: true, // 重復(fù)上傳    });    // 當(dāng)有文件被添加進(jìn)隊(duì)列的時(shí)候,添加到頁面預(yù)覽    this.uploader.on('fileQueued', (file) => {     this.$emit('fileChange', file);    });    this.uploader.on('uploadStart', (file) => {     // 在這里可以準(zhǔn)備好formData的數(shù)據(jù)     //this.uploader.options.formData.key = this.keyGenerator(file);    });    // 文件上傳過程中創(chuàng)建進(jìn)度條實(shí)時(shí)顯示。    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 = '文件上傳已達(dá)到最大上限數(shù)';     } else {      errorMessage = `上傳出錯(cuò)!請(qǐng)檢查后重新上傳!錯(cuò)誤代碼${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);   },   // 在隊(duì)列中移除文件   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需要自己去實(shí)現(xiàn)。 大概的代碼可以點(diǎn)這里 。
<vue-upload ref="uploader" url="xxxxxx" uploadButton="#filePicker" multiple @fileChange="fileChange" @progress="onProgress" @success="onSuccess"></vue-upload>
分片的原理及流程
當(dāng)我們上傳一個(gè)大文件時(shí),會(huì)被插件分片,ajax請(qǐng)求如下:
 
1.多個(gè)upload請(qǐng)求均為分片的請(qǐng)求,把大文件分成多個(gè)小份一次一次向服務(wù)器傳遞
2.分片完成后,即upload完成后,需要向服務(wù)器傳遞一個(gè)merge請(qǐng)求,讓服務(wù)器將多個(gè)分片文件合成一個(gè)文件
分片
可以看到發(fā)起了多次 upload 的請(qǐng)求,我們來看看 upload 發(fā)送的具體參數(shù):
 
第一個(gè)配置( content-disposition )中的 guid 和第二個(gè)配置中的 access_token ,是我們通過webuploader配置里的 formData ,即傳遞給服務(wù)器的參數(shù)
后面幾個(gè)配置是文件內(nèi)容,id、name、type、size等
其中 chunks 為總分片數(shù), chunk 為當(dāng)前第幾個(gè)分片。圖片中分別為12和9。當(dāng)你看到chunk是11的upload請(qǐng)求時(shí),代表這是最后一個(gè)upload請(qǐng)求了。
合并
分片后,文件還未整合,數(shù)據(jù)大概是下面這個(gè)樣子:
 
做完了分片后,其實(shí)工作還沒完,我們還要再發(fā)送個(gè)ajax請(qǐng)求給服務(wù)器,告訴他把我們上傳的幾個(gè)分片合并成一個(gè)完整的文件。
我怎么知道分片上傳完了,我在何時(shí)做合并?
webuploader插件有一個(gè)事件是 uploadSuccess ,包含兩個(gè)參數(shù), file 和后臺(tái)返回的 response ;當(dāng)所有分片上傳完畢,該事件會(huì)被觸發(fā),
我們可以通過服務(wù)器返回的字段來判斷是否要做合并了。
比如后臺(tái)返回了 needMerge ,我們看到它是 true 的時(shí)候,就可以發(fā)送合并的請(qǐng)求了。
 
存在的已知問題
在做單文件暫停與繼續(xù)上傳時(shí),發(fā)現(xiàn)了這個(gè)插件的bug:
1、當(dāng)設(shè)置的 threads>1 ,使用單文件上傳功能,即stop方法傳入file時(shí),會(huì)報(bào)錯(cuò) Uncaught TypeError: Cannot read property 'file' of undefined
出錯(cuò)的源碼如下:這是因?yàn)闀和r(shí)為了讓下一個(gè)文件繼續(xù)傳輸,會(huì)將當(dāng)前的pool池中pop掉暫停的文件流。這里做了循環(huán),最后一次循環(huán)的時(shí)候,v是undefined的。
 
2、設(shè)置的threads為1,能正常暫停,但是暫停后再繼續(xù)上傳是失敗的。
原理和上一個(gè)一樣,暫停時(shí)把當(dāng)前文件流在 pool 中全部 pop 了,當(dāng)文件開始 upload 的時(shí)候,會(huì)檢查當(dāng)期 pool ,而此時(shí)已經(jīng)沒有之前暫停的文件流了。
如果是針對(duì)所有文件整體的暫停和繼續(xù),功能是正常的。
總結(jié)
以上所述是小編給大家介紹的Vue2.0結(jié)合webuploader實(shí)現(xiàn)文件分片上傳功能,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)武林網(wǎng)網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注