<el-upload
ref="importExcel"
class="upload-demo"
:action="apiUrl"
:headers="myHeaders"
:http-request="uploadExcel"
:data="fileData"
:on-success="handleSuccess"
:on-error="handleError"
:on-remove="removeFile"
:before-upload="beforeUpload"
:file-list="fileList"
accept=".xls"
>
<el-button slot="trigger" type="primary" size="small" icon="el-icon-upload2">上传excel</el-button>
<div slot="tip" class="el-upload__tip">支持拓展名: .xls</div>
</el-upload>
1.action是默认的上传行为,配置上传地址即可
2.data是需要额外上传的参数
3.file-list上传的文件列表
4.before-upload上传文件之前的钩子,参数是上传的文件,一般在这
里限制文件类型,及文件大小
5.headers设置上传的请求头部
6.http-request覆盖默认的上传行为,自定义上传实现的方法
ps:当自定义上传时,action也是必须要配的参数,不过action参数的值可以随便写一个字符串,否则不配置或者为空字符串都会报错
好了,需要配置的几个关键的参数就这些。下边重点讲一下,如何自定义上传方法,及上传成功后返回文件乱码的问题【本文主要讲excel的上传及下载】
//自定义上传
uploadExcel(f){
let param = new FormData()
param.append('file',f.file)
axios.post(this.apiUrl, param, { responseType: 'arraybuffer' })
.then(response=>{
f.onSuccess(response)
})
.catch(({err}) => {
f.onError()
})
},
//上传成功后,再下载返回的excel文件,直接浏览器下载
handleSuccess(response, file, fileList) {
this.$notify({
title: '导入成功',
type: 'success',
duration: 2500
})
// 根据查询条件下载excel
let month = new Date().getMonth()+1
let day = new Date().getDate()
let year = new Date().getFullYear()
let fileName = year+"-"+month+"-"+day+ "-JMdata.xls"
let url = window.URL.createObjectURL(new Blob([response.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('id', 'downloadLink')
link.setAttribute('download', fileName)
document.body.appendChild(link)
link.click()
// 删除添加的a链接
let objLink = document.getElementById('downloadLink')
document.body.removeChild(objLink)
},
自定义请求,返回的excel文件流乱码,原因可能有2点
1.请求头没有配置,正确的配置和获取方法如下
:headers="myHeaders"
var token = localStorage.getItem('token')
export default {
name: "index",
components: {Upload},
data(){
return{
message:'',
fileList:[],
apiUrl:'/public/api/remote/uplodaExcel',
name:'',
code:'',
fileData:{},
myHeaders:{
Authorization:token
}
}
},
2.post请求的返回类型没有设置
let param = new FormData()
param.append('file',f.file) //上传参数格式,FormData
//this.apiUrl就是后台给我们的上传接口地址,params是参数,
//后台返回流文件,post请求的返回类型responseType必须为//arraybuffer,否则返回文件就是一堆乱码
axios.post(this.apiUrl, param, { responseType: 'arraybuffer' })
.then(response=>{
f.onSuccess(response)
})
网友评论