这是我们要实现的效果
element ui上的代码和效果如下:
<el-upload
class="avatar-uploader"
action="https://jsonplaceholder.typicode.com/posts/"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>
<script>
export default {
data() {
return {
imageUrl: ''
};
},
methods: {
handleAvatarSuccess(res, file) {
this.imageUrl = URL.createObjectURL(file.raw);
},
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
}
}
}
</script>
文章来源:https://www.toymoban.com/news/detail-530824.html
接下来我们需要将图片文件上传到接口中,实现代码如下:文章来源地址https://www.toymoban.com/news/detail-530824.html
<el-form-item label="分类图标" prop="imageUrl" required>
<el-upload class="avatar-uploader" :action="action" :headers="headers" :show-file-list="false"
:on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
style=" border: 1px dashed #d9d9d9;width: 178px;height: 178px;">
<img v-if="ruleForm.imageUrl" :src="ruleForm.imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
<script/>
export default {
components: { Pagination },
data() {
return {
action: `${process.env.VUE_APP_BASE_API}/biz/oss/uploadMinio`,
headers: {
Authorization: getToken(),
},
}
},
methods:{
handleAvatarSuccess(res, file) {
this.ruleForm.imageUrl = file.response.data.fullUrl;
},
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg' || 'image/jpg' || 'image/webp' || 'image/png';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传头像图片只能是 jgp,jpeg,webp,png格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
},
}
}
<script>
到了这里,关于element ui实现el-upload用户头像上传(单图上传)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!