download(data){
this.openPostWindow("/api/file/download",data);
},
//url 为请求地址, data为需要请求的数据
openPostWindow(url, data) {
//创建form表单,以下是form表单的各种参数
let tempForm = document.createElement("form");
tempForm.id = "tempForm";
tempForm.method = "post";
tempForm.action = url;
tempForm.target = 'blank';
//创建标签 <input></input> 标签 然后设定属性,最后追加为 form标签的子标签
for (let i in data) {
let hideInput = document.createElement("input")
hideInput.type = "hidden"
hideInput.name = i
hideInput.value = data[i]
tempForm.appendChild(hideInput)
}
if (document.all) {
tempForm.attachEvent("onsubmit", function () {
}); //IE
} else {
let subObj = tempForm.addEventListener("submit", function () {
}, false); //firefox
}
document.body.appendChild(tempForm);
if (document.all) {
tempForm.fireEvent("onsubmit");
} else {
tempForm.dispatchEvent(new Event("submit"));
}
tempForm.submit();//提交POST请求
document.body.removeChild(tempForm);//删除整个form标签
}
一次性下载多个附件
window.open方式只会调用一次,无法实现多次下载
//下载模板
downloadMould() {
//this.getCheckNodes()获取ztree选中节点的数据集合
let categoryValue = this.getCheckNodes();
if (categoryValue != null && categoryValue.length > 0) {
for (let val of categoryValue) {
//window.open(`/api/import/downloadFileMode?innerType=`+ val);
this.downloadFile(`/api/import/downloadFileMode?innerType=` + val);
}
} else {
return this.$Message.error("请先选择要下载的模板!")
}
},
downloadFile(url) {
const iframe = document.createElement("iframe");
iframe.style.display = "none"; // 防止影响页面
iframe.style.height = 0; // 防止影响页面
iframe.src = url;
document.body.appendChild(iframe); // 这一行必须,iframe挂在到dom树上才会发请求
// 5分钟之后删除
setTimeout(() => {
iframe.remove();
}, 5 * 60 * 1000);
},
浏览器下载和预览实现的区别(后台代码)
// 设置响应头后,浏览器会默认下载
response.setHeader("Content-Disposition", "attachment; filename=" + pathName);