element ui 上传文件并解析后端返回的文件流下载文件
<template>
<!-- 导入外部按钮 -->
<el-button style="color: #fff;position: relative;" type="primary">
<el-upload
style="color: #fff;height: 38px;width: 70px;line-height: 38px;"
class="upload-btn"
:action="uploadPath"
:headers="uploadHeader"
accept=".xls, .xlsx"
:show-file-list="false"
:http-request="handleAvatarSuccess">导入</el-upload>
</el-button>
</template>
<script>
import axios from "axios";
export default {
name: "fileUpload",
props: {
// 导入路径,由父组件传递
uploadUrl: {
type: String,
default: process.env.VUE_APP_BASE_API
}
},
data() {
return {
uploadPath: "", // 组件内接收导入路径的值
uploadHeader: {
// 导入时请求的请求头
Authorization: localStorage.getItem("toKenValue") || ""
}
};
},
created() {
this.uploadPath = this.uploadUrl;
},
methods: {
handleAvatarSuccess(response) {
// 传输文件
let formData = new FormData();
formData.append("file", response.file);
axios({
url: this.uploadPath,
method: "post",
headers: this.uploadHeader,
data: formData,
responseType: "blob" // 必须设置,不然拿不到后端给的blob对象
})
.then(res => {
if (res.data.type === "application/json") {
/**
* responseType: "blob" 会将请求回来的数据转换成blob对象
* blob对象的text方法可得到原始数据
*/
res.data.text().then(value => {
var { code } = JSON.parse(value);
if (code === 200) {
// 成功
this.$emit("handleAvatarSuccess", "success");
} else if (code !== 200 && code) {
// 失败
this.$emit("handleAvatarSuccess", "fail");
}
this.$Notification({
title: "提示",
message: code === 200 ? "导入成功" : "导入失败",
duration: 2500
});
});
// 当后端返回文件流的时候
} else {
var fileNameStr = res.headers["content-disposition"];
var fileName = decodeURIComponent(
fileNameStr.slice(fileNameStr.indexOf("%"))
); // 截取后端设置的文件名并转码
let url = window.URL.createObjectURL(res.data); // 拿到blob对象创建一个url地址
let link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.download = fileName; // 设置下载的文件名
document.body.appendChild(link);
link.click();
window.URL.revokeObjectURL(url); // 释放创建的url,防止内存污染,当浏览器关闭时也会清理创建的url
this.$Notification({
title: "提示",
message: "导入失败",
duration: 2500
});
}
})
.catch(err => {
console.log("err", err);
});
}
}
};
</script>
<style lang="stylus" scoped>
>>>.el-upload:focus {
border-color: #409EFF;
color: #fff;
}
.el-button {
padding: 0;
height: 38px;
}
</style>