图片上传和表单同时一起提交

1. <!-- 弹出框 -->
		<el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible">
			<el-form :model="form" :rules="rules" ref="form">
				<el-form-item label="商品名称" prop='goodsName' style="width:40%">
					<el-input v-model="form.goodsName" auto-complete="off" placeholder="请输入商品名称" size="medium"></el-input>
				</el-form-item>
				<el-form-item label="商品图片" prop='goodsImg'>

					<el-upload action="uploadAction" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
					 :limit="1" :show-file-list="true" name="img" ref="upload" :data="form" accept="image/png,image/gif,image/jpg,image/jpeg"
					 :headers="headers" :on-exceed="handleExceed" :auto-upload="false" :on-error="uploadError" :before-upload="handleBeforeUpload"
					 :on-change="changeFile">
						<i class="el-icon-plus"></i>
					</el-upload>
					<el-dialog :visible.sync="dialogVisible">
						<img width="50px" :src="dialogImageUrl" alt="">
					</el-dialog>
				</el-form-item>
				<el-form-item label="商品对应积分" prop='goodsIntegral'>
					<el-input v-model="form.goodsIntegral" auto-complete="off" placeholder="请输入积分" size="medium" type="number"></el-input>
				</el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="cancel">取 消</el-button>
				<el-button type="primary" @click="uploadFileFun('form')">确 定</el-button>
				"注意uploadFileFun('form')  括号内记得带引号不然可能会报validate is not defined"
			</div>
		</el-dialog>

2.data部分

		data() {
			return {
				//新增和编辑弹框标题
				titleMap: {
					addStore: '新增商品',
					editStore: "修改商品"
				},
				dialogStatus: "",
				//新增编辑弹出框
				dialogFormVisible: false,
				dialogVisible: false,
				//表格数据
				tableData: [],
				form: {
					id: '',
					goodsName: '',
					goodsImg: '',
					goodsIntegral: '',
				},
				rules: {
					goodsName: [{
						required: true,
						message: '请输入商品名称',
						trigger: 'blur'
					}],
					goodsIntegral: [{
						required: true,
						message: '请输入商品积分',
						trigger: 'blur'
					}],
				},
			headers: {
					Authorization: 'Bearer ' + window.localStorage.getItem("token")
				},
				dialogImageUrl: '', //图片回显
				uploadFiles: '', //formData img 文件
				goodsId: '', //判断是新增还是编辑
				}
  1. methods部分 手动上传图片 **var fd = new FormData()**添加
// 上传文件之前的钩子
			handleBeforeUpload(file) {
				console.log('按钮', this.titleMap)
				if (!(file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/jpg' || file.type ===
						'image/jpeg')) {
					this.$notify.warning({
						title: '警告',
						message: '请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片'
					})
				}
				let size = file.size / 1024 / 1024 / 2
				if (size > 2) {
					this.$notify.warning({
						title: '警告',
						message: '图片大小必须小于2M'
					})
				}

			},
			//图片上传超过数量限制
			handleExceed(files, fileList) {
				this.$message.error("上传图片不能超过1张!");
			},
			handleRemove(file, fileList) {
				this.$message.error("删除成功!");
			},
			// 图片上传失败时
			uploadError() {
				this.$message.error("图片上传失败!");
			},
			//预览图片
			handlePictureCardPreview(file) {
				this.dialogImageUrl = file.url;
				this.dialogVisible = true;
			},
			//文件改变时 on-change方法 ,fileList[0].raw 就是传给后端的值
			//filelist这个对象里面有很多属性,我们上传文件时,实际上传的是filelist列表中每一项的raw,只有raw可以正常上传, 获取到文件后,需要定义变量保存文件。所以需要获取filelist中的raw进行保存。
//这里我用的formdata上传多文件,console打印formdata,文件在控制台中显示的格式为binary。

			changeFile(file, fileList) {
				this.uploadFiles = fileList[0].raw 
			},
			uploadFileFun(formName) {
			
				this.$refs[formName].validate((valid) => {
					let fd = new FormData();
					fd.append('id', this.form.id);
					fd.append('goodsName', this.form.goodsName);
					fd.append('goodsIntegral', this.form.goodsIntegral);
					fd.append('img', this.uploadFiles);  
					
					let config = {
						headers: {
							'Content-Type': 'multipart/form-data'
						}
					}
					根据goodsID判断是编辑提交还是新增提交,主要针对新增编辑使用同一个弹框
					if (valid && !this.goodsId) {  
						this.$axios.post("接口地址", fd, config).then(res => {
							if (res.data.success == true) {
								this.dialogFormVisible = false
								this.$message({
									message: res.data.msg,
									type: 'success'
								});
								//新增完清空表单内容
								setTimeout(() => {
									this.$refs.form.resetFields();
								}, 200)

								this.reload()
							} else {
								this.$message.error(res.data.msg);
							}
						}).catch(res => {
							console.log(res)
						})
					} else {
						this.$axios.post("接口地址", fd, config).then(res => {
							if (res.data.success == true) {
								this.dialogFormVisible = false
								this.$message({
									message: res.data.msg,
									type: 'success'
								});
								//编辑完清空表单内容
								setTimeout(() => {
									this.$refs.form.resetFields();
								}, 200)

								this.reload()
							} else {
								this.$message.error(res.data.msg);
							}
						}).catch(res => {
							console.log(res)
						})
					}
				})
			},

		add() {
			this.dialogStatus = "addStore"
			this.dialogFormVisible = true
			this.goodsId = "" //新增商品是商品ID为空
		},
		// 取消
		cancel() {
			this.dialogFormVisible = false
			 this.$refs[formName].resetFields()
		},
		//编辑
		handleEdit(index, row) {
			this.form = this.tableData[index]
			this.dialogStatus = "editStore"
			this.goodsId = row.id
			this.currentIndex = index
			this.dialogFormVisible = true
		},
Logo

前往低代码交流专区

更多推荐