因為要上傳手機版的安裝包,上傳的檔案過大,為了保證良好的使用者體驗所以需要獲取上傳進度。結合了element_UI的進度條和上傳元件完成了上傳的動作。
html程式碼
<el-upload
action="上傳路徑"
list-type="text"
:file-list="fileList"
:before-upload="beforeAvatarUpload"
:http-request="Upload"
:show-file-list="false"
>
<div class="btn_upload">上傳安裝包</div>
</el-upload>
<el-progress v-show="showProgress" :text-inside="true" :stroke-width="15" :percentage="uploadPercent"> </el-progress>
el-upload提供了http-request方法覆蓋元件預設上傳事件,before-upload上傳前鉤子函式用來篩選檔案型別return false則會阻止上傳複製程式碼
data中return出的資料
xhr: new XMLHttpRequest(),
宣告一個全域性的ajax物件是為了呼叫關閉上傳事件函式
showProgress: false,
控制進度條顯示隱藏複製程式碼
beforeAvatarUpload(file) {
let name = file.name
var apk = name.substring(name.length-3,name.length)
字串擷取為了相容火狐,火狐瀏覽器獲取apk檔案的type為空
const isAPK = apk === "apk";
if (!isAPK) {
this.$message.error("上傳只能是 apk 格式安裝包!");
}
return isAPK;
},
複製程式碼
Upload(file) {
// 先要獲取後端簽名
let pro = new Promise((resolve, rej) => {
var res = JSON.parse(Cookies.get("sign"));
var timestamp = Date.parse(new Date()) / 1000;
if (res.expire - 3 > timestamp) {
resolve(res);
} else {
this.$http.get("/apiservice/oss/getSign").then(res => {
Cookies.set("sign", JSON.stringify(res.data));
resolve(res.data);
});
}
});
pro.then(success => {
var data = success;
var ossData = new FormData();
var date = new Date();
var s = date.getTime();
var y = date.getFullYear();
var m = date.getMonth() + 1;
var d = date.getDate();
ossData.append("name", file.file.name);
ossData.append(
"key",
data.dir + "/" + y + "/" + m + "/" + d + "/" + s + ".apk"
);
ossData.append("policy", data.policy);
ossData.append("OSSAccessKeyId", data.accessid);
ossData.append("success_action_status", 201);
ossData.append("signature", data.signature);
ossData.append("file", file.file, file.file.name);
this.xhr.open("post", data.host, true);
this.xhr.upload.addEventListener(
"progress",
this.progressFunction,
false
); //呼叫方法監聽上傳進度
this.xhr.onload = () => {
this.$message({
type: "success",
message: "上傳完成"
});
};
this.xhr.send(ossData);
});
},
progressFunction(event) {
// 設定進度顯示
if (event.lengthComputable) {
var percent = Math.floor(event.loaded / event.total * 100);
if (percent > 100) {
percent = 100;
}
this.uploadPercent = percent;
}
this.showProgress = true;
},
refUpload() {
//關閉上傳事件
this.xhr.abort();
},複製程式碼