vue+elementUi+upload上传文件检测类型和大小、includes、createObjectURL、upload、display、justify、radius


1、html

<div class="upload_box">
	<el-upload
		action="https://jsonplaceholder.typicode.com/posts/"
		:show-file-list="false"
		:on-success="handleAvatarSuccess"
		:on-error="handleOnError"
		:before-upload="beforeAvatarUpload"
	>
		<img
			v-if="ruleForm.coverImage"
			:src="ruleForm.coverImage"
			class="cover_image"
		/>
		<i v-else class="el-icon-plus avatar-uploader-icon"></i>
	</el-upload>
</div>

2、JavaScript

// 上传成功
handleAvatarSuccess(res, file) {
    
    
	console.log("handleAvatarSuccess:", res, file);
	this.ruleForm.coverImage = URL.createObjectURL(file.raw);
},

// 上传失败
handleOnError(error) {
    
    
	console.log("error:", error);
},

// 上传前
beforeAvatarUpload(file) {
    
    
	// 检测文件类型
	let isFileType = ["image/jpeg", "image/png", "image/jpg"].includes(file.type),
		// 文件大小为20M
		isFileSize = file.size / 1024 / 1024 < 20;
	
	if (!isFileType) this.$message.error("上传头像图片只能是jpeg/png/jpg格式!");
	if (!isFileSize) this.$message.error("上传头像图片大小不能超过20MB!");
	
	return isFileType && isFileSize;
},

3、css

.upload_box {
    
    
	display: flex;
	justify-content: center;
	align-items: center;
	width: 145px;
	height: 145px;
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
}

.cover_image {
    
    
	width: 100%;
	height: 100%;
}

猜你喜欢

转载自blog.csdn.net/weixin_51157081/article/details/125187141