<template>
<div>
<el-upload
class="upload-demo"
ref="upload"
action="api/upload"
:headers="config" //携带token
:on-preview="handlePreview"
:on-remove="handleRemove"
:file-list="fileList"
:auto-upload="false"
>
<el-button slot="trigger" size="large" type="primary">选取文件</el-button>
<el-button
style="margin-left: 10px;"
size="large"
type="success"
@click="submitUpload"
>上传并转化</el-button
>
</el-upload>
</div>
</template>
<script>
let token = JSON.parse(window.sessionStorage.getItem("token"));
export default {
data() {
return {
fileList: [],
fileName: ""
};
},
computed: {
config() {
return { Authorization: token || "" };
}
},
methods: {
handleRemove(file, fileList) {
console.log(file, fileList);
},
handlePreview(file) {
console.log(file);
},
submitUpload(param) {
let file = this.$refs.upload.uploadFiles.pop().raw; //这里获取上传的文件对象
let name = file.name;
this.fileName = name.slice(0, -4);
let formData = new FormData();
formData.append("file", file);
this.$axios
.post("http://xxxxx/xxxx/xxxxx", formData, {
responseType: "blob"
})
.then(res => {
// 转化为blob对象
let blob = new Blob([res.data], {
type: "application/octet-stream"
});
//文件名
let filename = `${this.fileName}.xls`;
// 将blob对象转为一个URL
var blobURL = window.URL.createObjectURL(blob);
// 创建一个a标签
var tempLink = document.createElement("a");
// 隐藏a标签
tempLink.style.display = "none";
// 设置a标签的href属性为blob对象转化的URL
tempLink.href = blobURL;
// 给a标签添加下载属性
tempLink.setAttribute("download", filename);
if (typeof tempLink.download === "undefined") {
tempLink.setAttribute("target", "_blank");
}
// 将a标签添加到body当中
document.body.appendChild(tempLink);
// 启动下载
tempLink.click();
// 下载完成移除元素
document.body.removeChild(tempLink);
// 释放blob对象
window.URL.revokeObjectURL(blobURL);
});
}
}
};
</script>
<style scoped>
</style>
使用element的upload上传文件并导出excel
于 2022-05-20 17:09:13 首次发布