element 表单提交图片(表单上传图片)

文章目录

  • 使用场景
  • 页面效果
  • 前端代码

使用场景

vue2 + element 表单提交图片
  1.点击【上传图片】按钮择本地图片(只能选择一张图片)后。
  2.点击图片,支持放大查看。
  3.点击【保存】按钮,提交表单。

页面效果

element 表单提交图片(表单上传图片)_第1张图片

前端代码

HTML

<div style="display: flex;align-items: center;">
	<el-upload :accept="pic_accept" action="" :on-change="uploadChange" :show-file-list="false">
		<el-button size="small" type="primary">上传图片el-button>
	el-upload>
	<div class="up_sy_logo_div" style="margin-left: 15px;">
		
		<el-image v-if="ruleForm.hrefn" style="width:100px;" :src="ruleForm.hrefn" :preview-src-list="ruleForm.hrefn ? [ruleForm.hrefn] : []">el-image>
	div>
div>

Vue data

pic_accept: ".jpg,.png,.jpeg,.bmp",
pic_maxsize: "5",//单位MB
ruleForm: {
	hrefn: ""
},
file: [],//暂存文件
submitLoading: false,//防止重复提交

Vue methods

uploadChange(file) {
	if (file.status !== 'success') return;
	if (!this.checkFile(file)) return;
	this.ruleForm.hrefn = URL.createObjectURL(file.raw);
	// 复刻文件信息
	this.file = file.raw;
},
checkFile(file) {
	//  判断图片类型
	if (this.pic_type) {
		let picTypeArr = this.pic_type.split(',');
		let isImage = false;
		picTypeArr.forEach(item => {
			if (file.raw.type === 'image/' + item) {
				isImage = true;
			}
		});
		if (!isImage) {
			message.error('上传图片只能是 (' + this.pic_type + ') 格式!');
			return false;
		}
	}
	//  判断图片大小
	if (this.pic_maxsize > 0) {
		let isLtNumM = file.size / 1024 / 1024 < this.pic_maxsize;
		if (!isLtNumM) {
			message.error('上传图片大小不能超过 ' + this.pic_maxsize + 'MB!');
			return false;
		}
	}
	return true;
},
submitForm(formName) {
	let _this = this;
	let params = JSON.parse(JSON.stringify(this.ruleForm));

	let formData = new FormData();
	Object.keys(params).forEach((key) => {
		if (Array.isArray(params[key])) {
			params[key].forEach((v) => {
				formData.append(key + '[]', v);
			});
		} else {
			formData.append(key, params[key]);
		}
	});
	if (this.file.length !== 0) {
		formData.append('file', this.file);
	}
	_this.submitLoading = true;
	//httpPost 是自定义的函数
	httpPost('你的服务器接口URL', formData).then(function (response) {
		let res = response.data;
		if (res.error === 0) {
			message.success(res.msg);
			_this.clearForm();
		} else {
			message.error(res.msg);
		}
		//_this.$emit("child-event-list");
	}).catch(function (error) {
		console.log(error);
	}).finally(function () {
		_this.submitLoading = false;
	});
}

服务端 PHP接受参数

$_POST;
$_FILES['file'];

你可能感兴趣的:(前端,vue.js,前端)