項目中多出有上傳文件的需求,使用現有的UI框架實現的過程當中,不知道什麼緣由,總會有一些莫名其妙的bug。好比用某上傳組件,明明註明(:multiple="false"),可實際上仍是能多選,上傳的時候依然發送了多個文件;又好比只要加上了(:file-list="fileList")屬性,但願能手動控制上傳列表的時候,上傳事件this.refs.[upload(組件ref)].submit()就不起做用了,傳不了。總之,懶得再看它怎麼實現了,我用的是功能,界面自己仍是要重寫的,若是堅持用也會使項目多不少沒必要要的邏輯、樣式代碼……html
以前用Vue作項目用的視圖框架有element-ui,團隊內部做爲補充的zp-ui,以及iview。框架是好用,可是針對本身的項目每每不能所有拿來用,尤爲是咱們的設計妹子出的界面與現有框架差別很大,改源碼效率低又容易致使未知的bug,因而本身就抽時間封裝了這個上傳組件。element-ui
<template>
<div class="content">
<label for="my-upload">
<span>上傳</span>
</label>
<my-upload
ref="myUpload"
:file-list="fileList"
action="/uploadPicture"
:data="param"
:on-change="onChange"
:on-progress="uploadProgress"
:on-success="uploadSuccess"
:on-failed="uploadFailed"
multiple
:limit="5"
:on-finished="onFinished">
</my-upload>
<button @click="upload" class="btn btn-xs btn-primary">Upload</button>
</div>
</template>
<script>
import myUpload from './components/my-upload'
export default {
name: 'test',
data(){
return {
fileList: [],//上傳文件列表,不管單選仍是支持多選,文件都以列表格式保存
param: {param1: '', param2: '' },//攜帶參數列表
}
},
methods: {
onChange(fileList){//監聽文件變化,增減文件時都會被子組件調用
this.fileList = [...fileList];
},
uploadSuccess(index, response){//某個文件上傳成功都會執行該方法,index表明列表中第index個文件
console.log(index, response);
},
upload(){//觸發子組件的上傳方法
this.$refs.myUpload.submit();
},
removeFile(index){//移除某文件
this.$refs.myUpload.remove(index);
},
uploadProgress(index, progress){//上傳進度,上傳時會不斷被觸發,須要進度指示時會頗有用
const{ percent } = progress;
console.log(index, percent);
},
uploadFailed(index, err){//某文件上傳失敗會執行,index表明列表中第index個文件
console.log(index, err);
},
onFinished(result){//全部文件上傳完畢後(不管成敗)執行,result: { success: 成功數目, failed: 失敗數目 }
console.log(result);
}
},
components: {
myUpload
}
}
</script>
複製代碼
父組件處理與業務有關的邏輯,我特地加入索引參數,便於界面展現上傳結果的時候可以直接操做第幾個值,並非全部方法都必須的,視需求使用。promise
<template>
<div>
<input style="display:none" @change="addFile" :multiple="multiple" type="file" :name="name" id="my-upload"/>
</div>
</template>
複製代碼
上傳文件,html部分就這麼一對兒標籤,不喜歡複雜囉嗦緩存
<script>
export default {
name: 'my-upload',
props: {
name: String,
action: {
type: String,
required: true
},
fileList: {
type: Array,
default: []
},
data: Object,
multiple: Boolean,
limit: Number,
onChange: Function,
onBefore: Function,
onProgress: Function,
onSuccess: Function,
onFailed: Function,
onFinished: Function
},
methods: {}//下文主要是methods的介紹,此處先省略
}
</script>
複製代碼
這裏定義了父組件向子組件須要傳遞的屬性值,注意,這裏把方法也當作了屬性傳遞,都是能夠的。bash
本身寫的組件,沒有像流行框架發佈的那樣完備和全面,另外針對開頭提到的綁定file-list就不能上傳了的問題(更多是個人姿式不對),本人也想極力解決掉自身遇到的這個問題,因此但願能對文件列表有絕對的控制權,除了action,把file-list也做爲父組件必需要傳遞的屬性。(屬性名父組件使用「-」鏈接,對應子組件prop中的駝峯命名)多線程
methods: {
addFile, remove, submit, checkIfCanUpload
}
複製代碼
methods內一共4個方法,添加文件、移除文件、提交、檢測(上傳以前的檢驗),下面一一講述:閉包
addFile({target: {files}}){//input標籤觸發onchange事件時,將文件加入待上傳列表
for(let i = 0, l = files.length; i < l; i++){
files[i].url = URL.createObjectURL(files[i]);//建立blob地址,否則圖片怎麼展現?
files[i].status = 'ready';//開始想給文件一個字段表示上傳進行的步驟的,後面好像也沒去用......
}
let fileList = [...this.fileList];
if(this.multiple){//多選時,文件所有壓如列表末尾
fileList = [...fileList, ...files];
let l = fileList.length;
let limit = this.limit;
if(limit && typeof limit === "number" && Math.ceil(limit) > 0 && l > limit){//有數目限制時,取後面limit個文件
limit = Math.ceil(limit);
// limit = limit > 10 ? 10 : limit;
fileList = fileList.slice(l - limit);
}
}else{//單選時,只取最後一個文件。注意這裏沒寫成fileList = files;是由於files自己就有多個元素(好比選擇文件時一會兒框了一堆)時,也只要一個
fileList = [files[0]];
}
this.onChange(fileList);//調用父組件方法,將列表緩存到上一級data中的fileList屬性
},
複製代碼
這個簡單,有時候在父組件叉掉某文件的時候,傳一個index便可。併發
remove(index){
let fileList = [...this.fileList];
if(fileList.length){
fileList.splice(index, 1);
this.onChange(fileList);
}
},
複製代碼
這裏使用了兩種方式,fetch和原生方式,因爲fetch不支持獲取上傳的進度,若是不須要進度條或者本身模擬進度或者XMLHttpRequest對象不存在的時候,使用fetch請求上傳邏輯會更簡單一些app
submit(){
if(this.checkIfCanUpload()){
if(this.onProgress && typeof XMLHttpRequest !== 'undefined')
this.xhrSubmit();
else
this.fetchSubmit();
}
},
複製代碼
fetchSubmit(){
let keys = Object.keys(this.data), values = Object.values(this.data), action = this.action;
const promises = this.fileList.map(each => {
each.status = "uploading";
let data = new FormData();
data.append(this.name || 'file', each);
keys.forEach((one, index) => data.append(one, values[index]));
return fetch(action, {
method: 'POST',
headers: {
"Content-Type" : "application/x-www-form-urlencoded"
},
body: data
}).then(res => res.text()).then(res => JSON.parse(res));//這裏res.text()是根據返回值類型使用的,應該視狀況而定
});
Promise.all(promises).then(resArray => {//多線程同時開始,若是併發數有限制,可使用同步的方式一個一個傳,這裏再也不贅述。
let success = 0, failed = 0;
resArray.forEach((res, index) => {
if(res.code == 1){
success++; //統計上傳成功的個數,由索引能夠知道哪些成功了
this.onSuccess(index, res);
}else if(res.code == 520){ //約定失敗的返回值是520
failed++; //統計上傳失敗的個數,由索引能夠知道哪些失敗了
this.onFailed(index, res);
}
});
return { success, failed }; //上傳結束,將結果傳遞到下文
}).then(this.onFinished); //把上傳總結果返回
},
複製代碼
xhrSubmit(){
const _this = this;
let options = this.fileList.map((rawFile, index) => ({
file: rawFile,
data: _this.data,
filename: _this.name || "file",
action: _this.action,
onProgress(e){
_this.onProgress(index, e);//閉包,將index存住
},
onSuccess(res){
_this.onSuccess(index, res);
},
onError(err){
_this.onFailed(index, err);
}
}));
let l = this.fileList.length;
let send = async options => {
for(let i = 0; i < l; i++){
await _this.sendRequest(options[i]);//這裏用了個異步方法,按次序執行this.sendRequest方法,參數爲文件列表包裝的每一個對象,this.sendRequest下面緊接着介紹
}
};
send(options);
},
複製代碼
這裏借鑑了element-ui的上傳源碼框架
sendRequest(option){
const _this = this;
upload(option);
function getError(action, option, xhr) {
var msg = void 0;
if (xhr.response) {
msg = xhr.status + ' ' + (xhr.response.error || xhr.response);
} else if (xhr.responseText) {
msg = xhr.status + ' ' + xhr.responseText;
} else {
msg = 'fail to post ' + action + ' ' + xhr.status;
}
var err = new Error(msg);
err.status = xhr.status;
err.method = 'post';
err.url = action;
return err;
}
function getBody(xhr) {
var text = xhr.responseText || xhr.response;
if (!text) {
return text;
}
try {
return JSON.parse(text);
} catch (e) {
return text;
}
}
function upload(option) {
if (typeof XMLHttpRequest === 'undefined') {
return;
}
var xhr = new XMLHttpRequest();
var action = option.action;
if (xhr.upload) {
xhr.upload.onprogress = function progress(e) {
if (e.total > 0) {
e.percent = e.loaded / e.total * 100;
}
option.onProgress(e);
};
}
var formData = new FormData();
if (option.data) {
Object.keys(option.data).map(function (key) {
formData.append(key, option.data[key]);
});
}
formData.append(option.filename, option.file);
xhr.onerror = function error(e) {
option.onError(e);
};
xhr.onload = function onload() {
if (xhr.status < 200 || xhr.status >= 300) {
return option.onError(getError(action, option, xhr));
}
option.onSuccess(getBody(xhr));
};
xhr.open('post', action, true);
if (option.withCredentials && 'withCredentials' in xhr) {
xhr.withCredentials = true;
}
var headers = option.headers || {};
for (var item in headers) {
if (headers.hasOwnProperty(item) && headers[item] !== null) {
xhr.setRequestHeader(item, headers[item]);
}
}
xhr.send(formData);
return xhr;
}
}
複製代碼
最後把請求前的校驗加上
checkIfCanUpload(){
return this.fileList.length ? (this.onBefore && this.onBefore() || !this.onBefore) : false;
},
複製代碼
若是父組件定義了onBefore方法且返回了false,或者文件列表爲空,請求就不會發送。