vue中elementUI组件Upload实现手动上传图片 - Go语言中文社区

vue中elementUI组件Upload实现手动上传图片


效果图:
手动点击上传图片

  1. 引入Upload组件
	<el-upload
			class="centerImg"
			:class="{hide:hideUploadIcon}"
			:action="' '"//请求地址,手动上传写为空
			list-type="picture-card"
			:on-preview="handlePictureCardPreviewIcon"
			:on-remove="handleRemoveIcon"
			:auto-upload="false"//false,手动上传
			:limit="1"//限制只能上传一张图片
			:on-change="handleAvatarChangeIcon"//文件状态改变时的钩子,
			ref="uploadicon"
			>
		    <i class="el-icon-plus"></i>
  </el-upload>
  <el-button @click="iconDialogVisible = false">取 消</el-button>
  <el-button type="primary" @click="saveIco()" >提 交</el-button>

2.点击上传前,取到图片路径

handleAvatarChangeIcon(file,fileList){
	const isJPG = file.raw.type === 'image/jpeg'
	const isPNG = file.raw.type === 'image/png'
	const isLt2M = file.raw.size / 1024 / 1024 < 0.5
	this.hideUploadIcon = fileList.length >= 1;
	if (!isPNG && !isJPG) {
		this.$message.error('上传图片只能是 JPG/PNG 格式!')
		return false
	} else if (!isLt2M) {
		this.$message.error('上传图片大小不能超过 200kb!')
		return false
	} else if (isLt2M && (isPNG || isJPG)) {
		this.iconformData.img = file.raw;//图片的url
		this.iconformData.name = file.name;//图片的名字
	}
}

3.点击上传,设置headers,传参格式为formdata

saveIco(){
		let config = {
	        timeout: 30000,
	        headers: {
	          "Content-Type": "multipart/form-data",//设置headers
	           token: getToken()
	        }
		};
		const formData = new FormData()
		for (const key in this.iconformData) {
			formData.append(key, this.iconformData[key]);//传参改为formData格式
		}
	    axios
	        .post(
	          SERVER_BASE_URL + "/gateway/dealFile/dealIcoImg",//请求后端的url
	          formData,
	          config
	        )
	        .then(res => {
				if(res.data.rtnCode==200){
					//上传成功
					
					
				}else{
					//上传失败
				}
	        })
	        .catch(error => {
	          //请求失败
	        });
}
版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_43835827/article/details/105634202
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-06-20 21:58:55
  • 阅读 ( 930 )
  • 分类:前端

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢