Element 使用multipart/form-data提交表单, 上传图片, 预览本体待上传图片
模板
<el-form ref="dataForm" :model="tempData" label-position="left" label-width="80px" style="width: 400px; margin-left:50px;">
<el-form-item label="人脸识别">
<template>
<el-upload
ref="upload"
class="avatar-uploader"
action="#"
:on-change="uploadFile"
:auto-upload="false"
:show-file-list="false"
>
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon" />
</el-upload>
</template>
</el-form-item>
<div slot="footer" class="dialog-footer">
<el-button @click="cancelForm">
取消
</el-button>
<el-button type="primary" @click="clickOk">
确认
</el-button>
</div>
</el-form>
script
<script>
import axios from 'axios'
export default {
data() {
return {
// 表单临时数据
tempData: {
verifyFace: ''
},
imageUrl: ''
}
},
methods: {
uploadFile(file) {
this.tempData.verifyFace = file.raw // 拿到文件的信息
//本地预览上传的图片
const reader = new FileReader()
// 读取完毕后获取结果
reader.onload = event => {
this.imageUrl = event.target.result
}
// 把文件对象作为一个 dataURL 读入
reader.readAsDataURL(file.raw)
},
// 提交编辑数据
async doCreate() {
const formData = new FormData()
formData.append('verifyFace', this.tempData.verifyFace)
formData.append('memberName', this.tempData.memberName)
formData.append('mobile', this.tempData.mobile)
formData.append('unit_id', this.tempData.unit_id)
axios.defaults.baseURL = 'http://域名'
axios.defaults.timeout = 50000
//header
axios.defaults.headers.post['Content-Type'] = 'multipart/form-data'
axios.defaults.headers.post['Token'] = getToken()
axios.post('/actionURL', formData)
.then(resp => {
if (resp.data.code) {
if (resp.data.code == 200) {
this.$message.success('创建成功')
this.fetchData()
this.cancelForm()
} else {
this.$message.error(resp.data.msg)
}
} else {
this.$message.error('创建成员失败, 请刷新后重试')
}
}, error => {
this.$message.error(error.response.data.msg)
})
},
// 点击确定添加,编辑
async clickOk() {
this.$refs.dataForm.validate(async valid => {
if (!valid) return null
await this.doCreate()
})
},
// 取消表单
cancelForm() {
this.tempData = {
memberName: '',
mobile: '',
verifyFace: ''
}
this.$refs.dataForm.resetFields()
this.dialogFormVisible = false
this.dialogStatus = ''
},
// 修改页面条数
handleSizeChange(val) {
this.queryParams.pageSize = val
this.fetchData()
},
// 修改页数
handleCurrentChange(val) {
this.queryParams.page = val
this.fetchData()
},
// 页面位置根据基地获取列表
changeListUnit() {
this.handleCurrentChange(1)
}
}
}
</script>
css
<style scoped>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>