?這是我們要實現(xiàn)的效果
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>
文章來源:http://www.zghlxwxcb.cn/news/detail-530824.html
?接下來我們需要將圖片文件上傳到接口中,實現(xiàn)代碼如下:文章來源地址http://www.zghlxwxcb.cn/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實現(xiàn)el-upload用戶頭像上傳(單圖上傳)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!