做项目时,需要上传文件,但是按钮是循环渲染出来的
使用
this.$refs.file.click()
提示
File chooser dialog can only be shown with a user activation.
修改为
<input type="file" ref="upload" @change="uploadFile" accept=".xlsx, xls" style="display: none"/>
new MouseEvent(‘click’)
this.$refs.upload.dispatchEvent(new MouseEvent('click'))
uploadFile(){
var that = this;
debugger
const inputFile = this.$refs.upload.files[0];
if(inputFile){
if(inputFile.size > 100000) {
this.$message.warning("文件过大");
return;
}
} else {
this.$message.warning('请选择要上传的文件')
}
},
上传成功要执行清空value,不然再次点击可能不会触发上传操作
this.$refs.upload.value = null;
发现无法下载 发现是因为拦截器中将数据强制转换为了formdata格式
service.interceptors.request.use(async config => {
store.state.isLoading = true
// 转换成form-data类型
config.transformRequest = [function(data) {
return qs.stringify(data)
}]
config.headers['token'] = '333'
return config
}, function(err) {
// store.state.isLoading = false
// console.log(err)
})
let res = await downloadExcelTemplate(data)
let blob = new Blob(res.data)
console.log('下载模板',blob)
const url = window.URL.createObjectURL(blob)
let link = document.createElement('a') //创建a标签
link.style.display = 'none' //将a标签隐藏
link.href = url //添加下载链接
link.setAttribute('download', source.templatename) // 此处注意,要给a标签添加一个download属性,属性值就是文件名称 否则下载出来的文件是没有属性的,空白白
document.body.appendChild(link)
link.click() //执行a标签
使用插件XLSX(待补充)
<a-upload
accept=".xls, .xlsx"
name="file"
action=""
:showUploadList="false"
:customRequest="customRequest"
>
<a-button> 批量导入 </a-button>
</a-upload>
import XLSX from 'xlsx'
customRequest(content) {
var reader = new FileReader()
reader.readAsBinaryString(content.file)
reader.onload = (e) => {
let data = e.target.result //获取上传的文件内容
let wb = XLSX.read(data, {
type: 'binary'
})
let sheet1 = wb.Sheets[wb.SheetNames[0]]
let importData = XLSX.utils.sheet_to_json(sheet1, {
range: 1,
header: ["payee_name","account_no","bank_name","is_public"]
})
console.log(importData)
}
},
后端设置的文件名称在相应头的 "content-disposition"中