【Element-UI上传照片-转base64】

该博客详细介绍了如何使用Element-UI组件进行图片上传,并在前端将上传的图片转换为Base64编码。在上传过程中,还包含了文件类型的检查和大小限制。同时,提供了getBase64函数用于读取文件并转化为Base64字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Element-UI上传照片-转base64

https://blog.youkuaiyun.com/weixin_43185419/article/details/120332799

<el-upload
	ref="elupload"
	class="avatar-uploader"
	action="#"
	:http-request="httpRequest"
	 :show-file-list="false"
	:before-upload="beforeAvatarUpload"
	>
	 <img v-if="imageUrl" :src="imageUrl" class="avatar">
	<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
beforeAvatarUpload(file) {
	console.log(file)
 	this.imgName = file.name;
    this.nowFile = file;
},
httpRequest(data){
	this.imageUrl = URL.createObjectURL(data.file);
	//这是限制上传文件类型 
	const isPFX = data.file.type === 'image/jpeg' || data.file.type === 'image/jpg' || data.file.type === 'image/png';
	const isLt2M = data.file.size / 1024 / 1024 < 2;
	if (!isPFX) {
	 	this.$message.error("上传头像图片只能是 JPG、PNG、JPEG 格式!");
	}else if (!isLt2M) {
	 	this.$message.error("上传文件大小不能超过 2MB!");
	}else{
		this.getBase64(data.file).then(resBase64 => {
	 	this.fileBase64 = resBase64.split(',')[1]  //直接拿到base64信息
	 	this.tempUrl = resBase64.split(',')[1]
	 })
	}
},
//这个file参数 也就是文件信息,你使用 插件 时 你就可以打印出文件信息 看看嘛
 getBase64(file) {
       return new Promise((resolve, reject) => {
         let reader = new FileReader();
         let fileResult = "";
         reader.readAsDataURL(file);
      //开始转
         reader.onload = function() {
           fileResult = reader.result;
         };
      //转 失败
         reader.onerror = function(error) {
           reject(error);
         };
      //转 结束  咱就 resolve 出去
         reader.onloadend = function() {
           resolve(fileResult);
         };
       });
     },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值