使用了iview组件库
components文件中创建upload_file 文件
upload_file.vue
<template>
<div>
<input :id="buttonId" type="file" @change="changeAction" style="display: none;" />
<Button icon="ios-cloud-upload-outline" type="primary" @click="triggerFileSelecter"> {{ buttonName }} </Button>
</div>
</template>
<script>
export default {
props: {
//文件选择器change事件
changeAction: {
type: Function
},
//按钮的名称
buttonName: {
type: String
},
//按钮的ID
buttonId: {
type: String
},
},
methods: {
triggerFileSelecter() {
document.querySelector("#" + this.buttonId).click();
}
}
}
</script>
<style lang="less" scoped>
</style>
index.vue
js部分
页面中引用组件
import uploadFile from '@/components/upload_file/upload_file.vue'
声明组件
components: {
uploadFile
},
html中使用组件
<uploadFile
:button-id="'user_list_upload'"
:change-action="upload_users_excel"
:button-name="'上传Execl'"
></uploadFile>
upload_users_excel ,上传方法
upload_users_excel(e) { // Execl表上传
// 点击上传获取到上传的文件
let test_uploadfile = e.target.files;
// console.log(test_uploadfile,'test_uploadfile');
// 创建一个空对象实例
let formdata = new FormData()
// 添加一个新值到 FormData 对象内的一个已存在的file键中
formdata.append("file", test_uploadfile[0])
// console.log(formdata,'formdata');
// 页面加载蒙层
this.$Spin.show()
// 这里是响应需求,在用户上传时,上传的表格不符合规范,会返回一个execl表格,此时需要再将返回的execl表格下载
upload_sku_config_excel(formdata).then(async res => {
// 使用async将返回的数据转成Promise 对象
if(res.data.type == "application/json") {
// 使用async将返回的数据转成Promise 对象
let retJson = await res.data.text();
// console.log(retJson,'---await res.data.text();');
retJson = JSON.parse(retJson);
// console.log(retJson,'---JSON.parse(retJson);');
console.info(retJson);
if (retJson && retJson.errCode != 0) {
this.$Message.error(retJson.errMsg)
this.$Spin.hide()
this.reload()
return
}
this.$Message.success("上传成功")
this.$Spin.hide()
this.reload()
}else{
// 这里是响应需求,在用户上传时,上传的表格不符合规范,会返回一个execl表格,此时需要再将返回的execl表格下载(正常上传就不需要else部分)
console.log("zou下载");
let blob = new Blob([res.data]);
let url = window.URL.createObjectURL(blob);
let link = document.createElement('a');
link.href = url;
link.setAttribute('download', '错误信息.xlsx');
document.body.appendChild(link);
link.click();
this.$Message.success("错误信息正在下载")
this.reload()
this.$Spin.hide()
}
})
},