1.html
<div>
<el-button @click="downloadClick">下载</el-button>
<input type="file" @change="onClick" />
<el-progress :percentage="progresses"></el-progress>
</div>
2.初始化字段
progresses: 0,
3.上传方法
onClick(event) {
const files = event.target.files;
const formData = new FormData();
// 循环遍历所有选中的文件,添加到FormData对象中
for (let i = 0; i < files.length; i++) {
formData.append("file", files[i]);
}
let xhr = new XMLHttpRequest();
xhr.open("POST", "http://192.168.0.90:8080/upload", true);
var _this = this;
xhr.upload.onprogress = function (event) {
if (event.lengthComputable) {
// 计算上传进度百分比
const percentage = parseInt((event.loaded / event.total) * 100);
_this.progresses = percentage;
console.log(_this.progresses);
}
};
xhr.send(formData);
},
4.下载方法
downloadClick() {
let xhr = new XMLHttpRequest();
xhr.open("POST", "http://192.168.0.90:8080/download", true);
var _this = this;
xhr.onprogress = function (event) {
if (event.lengthComputable) {
// 计算上传进度百分比
const percentage = parseInt((event.loaded / event.total) * 100);
_this.progresses = percentage;
console.log(_this.progresses);
}
};
xhr.responseType = "blob"; //很关键
xhr.onload = function (e) {
if (xhr.readyState == 4 && xhr.status == 200) {
//获取所有响应头
let headers = xhr.getAllResponseHeaders();
let fileName = "";
//获取指定响应头,从响应头中获取文件名
let temp = xhr.getResponseHeader('Content-Disposition');
let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
let matches = filenameRegex.exec(temp);
if (matches != null && matches[1]) {
fileName = matches[1].replace(/['"]/g, ""); // 解析出文件名 Backup-20230307152152.tgz
}
console.log('fileName:',fileName);
const url = window.URL.createObjectURL(xhr.response);
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", fileName);
document.body.appendChild(link);
link.click();
// _this.progresses = 0
}
};
xhr.send();
},
5.效果(也可以下载其他类型的文件)