el-upload如何灵活使用http-request自定义上传方法?
前言
当el-upload上传文件成为可选时,没有选择文件使用组件的submit()方法是不会产生任何动作的。因此本例就是为了使el-upload组件更灵活的使用而设计的。
思路
- 使用http-request属性获取选择的文件:
在该属性中,给出调用的函数function(例如selfUpload),function会接收到一个参数,假设命名为config,config中包含了file文件的所有信息,包括他的二进制数据、名称以及大小等。 - 组件选取文件时,做一个标记
选取文件时,利用组件的on-change属性,给uploadData.fileName赋值一个选取文件的名称,以标记是否选取了文件;
取消选取时,利用on-remove属性,将uploadData.fileName = null 置空。 - 通过判断标记,使用submit方法或者直接调用自定义上传函数
运用示例
html
<el-upload
name="file"
ref="upload"
action="http://localhost:8080/upload"
:on-change="(file, fileList) => this.uploadData.fileName = file.name"
:on-remove="(file, fileList) => this.uploadData.fileName = null"
:on-success="handleSuccess"
:on-error="handleError"
:http-request="selfUpload"
:auto-upload="false"
>
</el-upload>
<el-button type="primary" @click="clickUpload">点我上传</el-button>
js
selfUpload(config){
console.log('config', config)
let formData = config.file?{...this.uploadData, 'file(文件属性名)': config.file}:this.uploadData // 没有选取文件,不传递 file(文件属性名) 属性
this.axios.post('/upload', formData).then(res => {
this.$message.success('Success!')
})
}
// config.file即二进制数据,config.file.name文件名称,config.file.size文件大小,其他可以打印config看看
// 上传触发(二选一)
// 1. 只是新增使用
clickUpload(){
if (this.uploadData.fileName){
this.$refs.upload.submit()
}else{
this.selfUpload({file: null})
}
}
// 2. 编辑和新增一体
// 触发编辑时,给this.uploadData.fileName = this.uploadData.file赋值
// this.uploadData.fileName变化时代表选取了文件,没有选取,则依然相等,从而选择不同的上传策略
clickUpload(){
if (this.uploadData.fileName !== this.uploadData.file){
this.$refs.upload.submit()
}else{
this.selfUpload({file: null})
}
}
注意:传输数据形式一定要是multipart/form-data
,如是其他可能会不上传,亲测趟坑。