1、组件el-upload加上multiple,auto-upload,on-change
<el-upload ... :multiple="multiple" :auto-upload="!multiple" :on-change="handleChange" :on-success="onSuccess">
2、通过on-change进行多次单文件上传
<script>
import axios from 'axios'
import api from 'shared/api'
export default {
props: {
multiple: {
type: Boolean,
default: true
}
},
data () {
return {
tempAxios: '',
imgData: Params({}, api.upload.upload),
token: { Authorization: localStorage.getItem('token') },
}
},
created () {
this.createNewAxios()
},
methods: {
// 创建新的axios
createNewAxios () {
this.tempAxios = axios.create({
baseURL: '',
timeout: 5000,
headers: {
'Content-Type': 'multipart/form-data',
...this.token
}
})
},
handleChange (file, fileList) {
if (!this.multiple) return
this.submitUpload(file, fileList)
},
// 上传到服务器
submitUpload(file, fileList) {
const formData = new FormData() // new formData对象
for (let key in this.imgData) {
formData.append(key, this.imgData[key])
}
formData.append('fileName', file.raw)
this.tempAxios.post(this.imgUrl, formData).then(res => {
this.onSuccess(res.data, file, fileList)
})
},
... // 原有function保持不变
}
}
</script>