在使用elementui上传组件时,可以一次选择多个文件上传,设置:multiple="true"可以选择多个文件,但是文件请求的时候还是分开请求,多少个图片请求多少次。
现在需求时一次请求上传所有选中的图片
主要步骤:(1)通过elementui组件选取需要上传图片(2)封装上传函数
代码:
hmtl部分:
<el-dialog title="选择上传图片" :visible.sync="dialogVisible_up_image" width="30%">
<el-upload
ref="upload"
class="upload-demo"
action="" <!-- 因为是自定义的上传方式,此处可以不填 -->
:multiple="true"
:auto-upload="false"
:before-upload="beforeAvatarUploadImage"
:file-list="fileList"
:limit="6"
:on-change="handleChange"
list-type="picture"
>
<el-button slot="trigger" size="small" type="primary">选取图片</el-button>
<el-button
style="margin-left: 10px;"
size="small"
type="primary"
@click="uploadForm" <!-- 自定义的上传函数(核心) -->
>上传到服务器</el-button>
<div slot="tip" class="el-upload__tip">只能上传png、jpg格式的图片</div>
</el-upload>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible_up_image = false">取 消</el-button>
<el-button type="primary" @click="dialogVisible_up_image = false">确 定</el-button>
</span>
</el-dialog>
js部分
beforeAvatarUploadImage(file) {
const isJpeg = file.type === 'image/png' || file.type === 'image/jpg'
if (!isJpeg) {
this.$message.error('请选择正确的文件格式上传')
}
return isJpeg
},
handleChange(fileList) {
this.fileList.push(fileList)
},
uploadForm() {
if (this.fileList.length === 0) {
this.$message.warning('请选取文件')
return
}
const formData = new FormData()
this.fileList.forEach(file => {
formData.append('files', file.raw)
})
formData.append('userId', this.userId)
this.$axios.post('http://117.78.49.148:8088/medical-care/common/uploadFile/FullPaths', formData).then(res => {
this.$message.success('图片上传成功!')
setTimeout(() => {
this.dialogVisible_up_image = false
}, 500)
}).catch(res => {
this.$message.success('图片上传失败!')
setTimeout(() => {
this.dialogVisible_up_image = false
}, 500)
})
this.fileList = []
}
结果所示
