在自定义上传的场景下,我们通过使用 :http-request="handleFileUpload"
属性来指定自定义的上传函数, handleFileUpload
将会负责实际处理文件的上传操作,并与后端进行交互。所以不需要指定具体的 action——指定文件上传的目标地址(后端接收文件的 API 地址),但需要将 action
设置为空字符串,是因为action属性为必传,需要传入一个值来满足校验要求。
<el-upload
ref="upload"
class="upload-demo"
:action="''"
:on-remove="handleRemove"
:before-upload="beforeUpload"
:file-list="fileList"
:http-request="handleFileUpload"
accept=".xlsx,.XLSX,.xls,.XLS"
:show-file-list="false"
>
<el-button slot="trigger" type="primary" size="mini">
导入文件</el-button>
<div slot="tip" class="el-upload__tip">只能上传xlsx/pngxls</div>
</el-upload>
:before-upload="beforeUpload"文件上传之前的自定义操作,如再次校验文件格式、大小。。。
beforeUpload(file) {
// 如下:在此再次校验文件格式,因为accept虽然会过滤其他文件格式,但若用户强制选择上传其他文件格式时。
const testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
const isXlsx = testmsg === 'xlsx' || testmsg === 'XLSX' || testmsg === 'xls' || testmsg === 'XLS'
if (!isXlsx) {
this.$message({
message: '上传文件只能是 xlsx/xls 格式',
type: 'warning'
})
return isXlsx //可以返回 false 阻止文件上传
}
},
:http-request="handleFileUpload":
覆盖默认的上传行为,实现自定义文件上传函数,接收 `file` 参数。
handleFileUpload(file) {
const formDate = new FormData()
formDate.append('file', file.file)
formDate.append('orderId', this.form.id)//上传的其他参数
// 上传的接口需要定义Content-type
axios({
url:'/api/hasUploadfile',
data:formDate,
headers: { 'Content-type': 'multipart/form-data'},
method: 'post',
}).then((res) => {
this.fileList = []
this.fileList.push(file.file)
this.$message.success('上传成功!')
}).catch((error) => {
console.log(error, 'error')
this.$refs.upload.clearFiles()
})
},
:on-remove="handleRemove":删除文件之前的钩子,参数为上传的文件和文件列表,若返回 false 或者返回 Promise 且被 reject,则停止删除。
handleRemove(file, fileList) {
this.fileList = fileList
},