vue中文件上传阿里云并获取上传进度
因为要上传手机版的安装包,上传的文件过大,为了保证良好的用户体验所以需要获取上传进度。结合了element_UI的进度条和上传组件完成了上传的动作。html代码<el-uploadaction="上传路径"list-type="text":file-list="fil...
·
因为要上传手机版的安装包,上传的文件过大,为了保证良好的用户体验所以需要获取上传进度。结合了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();
},
更多推荐
已为社区贡献1条内容
所有评论(0)