手动上传
用的是生成input标签,唤起的文件上传,选取文件后然后生成formData二级制流传给后端这种操作
uploadEvent(){
const _this = this;
const fileType = ['xls','xlsx']
const inputFile = document.createElement("input")
inputFile.type = "file"
inputFile.style.display = "none"
document.body.appendChild(inputFile)
inputFile.click()
inputFile.addEventListener("change",function() {
const file = inputFile.files[0];
var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
console.log('file.name0----',file.name,testmsg)
if (!fileType.includes(testmsg)) {
_this.$message.warning("上传的文件格式只能是xls,xlsx");
document.body.removeChild(inputFile);
return false;
}
const formData = new FormData();
formData.append("file", file);
_this.$request.post({
url: xxx/import',
responseType: "blob",
loading: true,
data:formData,
headers: { "Content-Type": "multipart/form-data;boundary" },
}).then((res) => {
console.log('导入回执===',res)
}).finally(()=> {
document.body.removeChild(inputFile);
})
})
},```
手动导出
我这里因为涉及到权限的问题,所以用的后端接口获取的文件数据下载,
downloadEvent() {
let params=new Object()
if(Object.keys(this.searchformCallback).length>0){
params.body={...this.searchformCallback}
}else{
params.body={
targetCode:"",
targetName:"",
}
}
const tablePage={...this.tablePage,total:100}
params={...params,...tablePage}
this.$request.post({
url: 'xxx/export',
responseType: "blob",
_backAll: true,
loading: true,
data:params
}).then((res) => {
console.log(res)
let blob = new Blob([res.data])
let dlNameDisposition = res.headers['content-disposition']
let fileName =
decodeURIComponent(dlNameDisposition.split('filename=')[1]) || ''
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, fileName)
} else if (res.data.type == 'application/json') {
return res.data //自行处理
} else {
var link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = fileName
link.click()
//释放内存
window.URL.revokeObjectURL(link.href)
}
});
},
模板下载
模板下载不同于导出,导出使用的formData形式,而模板下载时参数时不传的,前端自己对后端的excel流的解析
//下载模板
downloadTemplateEvent(){
this.$request.post({
url: '/kas/api/kasKaiTargetConfig/template',
responseType: "blob",
_backAll: true,
loading: true,
data:''
}).then((res) => {
console.log('模板下载---',res)
if (res.data) {
let attrs = res.headers['content-disposition'].split(';')
// 获取文件名
let fileName = ''
// 不用管fileName在第几个位置,只要=前面是fileName,就取=后面的值
for (let i = 0, l = attrs.length; i < l; i++) {
let temp = attrs[i].split('=')
if (temp.length > 1 && temp[0] === 'fileName') {
fileName = temp[1]
break
}
}
fileName = decodeURIComponent(fileName)
// 获取数据类型
let type = res.headers['content-type'].split(';')[0]
let blob = new Blob([res.data], { type: type })
const a = document.createElement('a')
// 创建URL
const blobUrl = window.URL.createObjectURL(blob)
a.download = fileName
a.href = blobUrl
document.body.appendChild(a)
// 下载文件
a.click()
// 释放内存
URL.revokeObjectURL(blobUrl)
document.body.removeChild(a)
} else {
console.log('error', data)
}
})
},