这个是上传中途的截图
代码部分
<template>
<div class="flex">
<progress
id = "progressBar"
value = "0"
max = "100"
style = "width: 300px;"
></progress>
<span id="percentage"></span><span id="time"></span>
<br /><br />
<input
type = "file"
id = "file"
name = "myfile"
/>
<input
type = "button"
@click = "UpladFile()"
value = "上传"
/>
<input
type = "button"
@click = "cancleUploadFile()"
value = "取消"
/>
</div>
</template>
<script>
export default {
name: "flex",
data() {
return {
xhr : "",
ot : "",
oloaded: ""
};
},
mounted() {},
methods: {
//上传文件方法
UpladFile() {
let _this = this;
let fileObj = document.getElementById("file").files[0]; // js 获取文件对象
let url = ""; // 接收上传文件的后台地址
let form = new FormData(); // FormData 对象
form.append("file", fileObj); // 文件对象
_this.xhr = new XMLHttpRequest(); // XMLHttpRequest 对象
_this.xhr.open("post", url, true); //post方式,url为服务器请求地址,true 该参数规定请求是否异步处理。
_this.xhr.onload = _this.uploadComplete; //请求完成
_this.xhr.onerror = _this.uploadFailed; //请求失败
_this.xhr.upload.onprogress = _this.progressFunction; //【上传进度调用方法实现】
_this.xhr.upload.onloadstart = function() {
//上传开始执行方法
_this.ot = new Date().getTime(); //设置上传开始时间
_this.oloaded = 0; //设置上传开始时,以上传的文件大小为0
};
_this.xhr.send(form); //开始上传,发送form数据
},
//上传成功响应
uploadComplete(evt) {
//服务断接收完文件返回的结果
let data = evt.target.responseText;
if (data.success) {
alert("上传成功!");
} else {
alert("上传失败!");
}
},
//上传失败
uploadFailed(evt) {
alert("上传失败!");
},
//取消上传
cancleUploadFile() {
let _this = this;
_this.xhr.abort();
},
//上传进度实现方法,上传过程中会频繁调用该方法
progressFunction(evt) {
let _this = this;
let progressBar = document.getElementById("progressBar");
let percentageDiv = document.getElementById("percentage");
// event.total是需要传输的总字节,event.loaded是已经传输的字节。如果event.lengthComputable不为真,则event.total等于0
if (evt.lengthComputable) {
progressBar.max = evt.total;
progressBar.value = evt.loaded;
percentageDiv.innerHTML =
Math.round((evt.loaded / evt.total) * 100) + "%";
}
let time = document.getElementById("time");
let nt = new Date().getTime(); //获取当前时间
let pertime = (nt - _this.ot) / 1000; //计算出上次调用该方法时到现在的时间差,单位为s
_this.ot = new Date().getTime(); //重新赋值时间,用于下次计算
let perload = evt.loaded - this.oloaded; //计算该分段上传的文件大小,单位b
this.oloaded = evt.loaded; //重新赋值已上传文件大小,用以下次计算
//上传速度计算
let speed = perload / pertime; //单位b/s
let bspeed = speed;
let units = "b/s"; //单位名称
if (speed / 1024 > 1) {
speed = speed / 1024;
units = "k/s";
}
if (speed / 1024 > 1) {
speed = speed / 1024;
units = "M/s";
}
speed = speed.toFixed(1);
//剩余时间
let resttime = ((evt.total - evt.loaded) / bspeed).toFixed(1);
time.innerHTML =
",速度:" + speed + units + ",剩余时间:" + resttime + "s";
if (bspeed == 0) time.innerHTML = "上传已取消";
}
}
};
</script>
<style scoped>
.flex {
width : 100%;
height : 500px;
background-color: #fff;
padding : 20px;
}
</style>
找的资料,然后写入这个vue项目,需要优化的地方自行优化
这里卿洋
愿喜❤️
网友评论