方法一、
//和其他一样添加prop属性
<el-form ref="form" :model="form" :rules="rules" label-width="140px">
<el-form-item label="营业执照上传" prop="imageId">
<el-upload
ref="upload"
class="avatar-uploader"
:headers="upload.headers"
:disabled="upload.isUploading"
:action="upload.url + '?file=' + upload.updateSupport"
:show-file-list="false"
:limit="1"
accept=".jpg, .jpeg, .png"
:on-progress="handleFileUploadProgress"
:on-success="handleFileSuccess"
:on-error="handleFileError"
:auto-upload="true"
>
<img v-if="form.imageId" :src="form.imageUrl" class="avatar" />
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
</el-form>
//data里面添加rules校验规则
rules: {
imageId: [{ required: true, message: '请上传营业执照', trigger: 'change' }]
},
//在methods里添加图片上传成功的回调方法handleFileSuccess
handleFileSuccess(response, file, fileList) {
this.form.imageId = response;
this.form.imageUrl = baseURL + response;
this.upload.isUploading = false;
this.$refs.form.clearValidate('imageId') //清除图片校验文字
},
方法二、
此方法是通过一个接口将图片和form表单一次提交到后端,网上大部分都是方法一。
//和其他一样添加prop属性
<el-form ref="form" :model="form" :rules="rules" label-width="140px">
<el-form-item label="营业执照上传" prop="imageUrl">
<el-upload
ref="upload"
class="avatar-uploader"
:headers="upload.headers"
:disabled="upload.isUploading"
:action="upload.url + '?file=' + upload.updateSupport"
:show-file-list="false"
:limit="1"
accept=".jpg, .jpeg, .png"
:on-change="handleFileChange" //添加文件改变时钩子
:on-progress="handleFileUploadProgress"
:on-success="handleFileSuccess"
:on-error="handleFileError"
:auto-upload="false" //改为手动上传
:data="form" //携带其他参数上传
>
<img v-if="form.imageUrl" :src="form.imageUrl" class="avatar" />
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="submitClick">确 定</el-button>
<el-button @click="cancelClick">取 消</el-button>
</div>
//data里面添加rules校验规则
rules: {
imageUrl: [{ required: true, message: '请上传营业执照', trigger: 'change' }]
},
upload: {
// 是否显示弹出层(用户导入)
open: false,
// 弹出层标题(用户导入)
title: '',
// 是否禁用上传
isUploading: false,
// 是否更新已经存在的用户数据
updateSupport: 0,
// 设置上传的请求头部
headers: { Authorization: getToken() },
// 上传的地址
url: baseURL + '/t-mchinfo/add',
fileList: ''
}
//在methods里添加图片上传成功的回调方法handleFileSuccess
handleFileChange(file, fileList) {
//判断图片列表长度大于0时,代表已上传本地图片
if(fileList.length > 0){
this.form.imageUrl = file.url; //image图片回显
this.$refs.form.clearValidate('imageUrl') //清除图片文字校验
}
}
// 对话框点击提交
submitClick() {
this.$refs['form'].validate(valid => {
if (valid) {
this.$refs.upload.submit() //手动提交upload
}
});
},