vue 使用element Upload头像上传
这里使用element Upload 用户头像上传HTML部分<el-uploadclass=“avatar-uploader”action=" 123"// 这个地址不是必须的。可随便写:show-file-list=“false”:on-success=“handleAvatarSucce
·
这里使用element Upload 用户头像上传
HTML部分
<el-upload
class="avatar-uploader"
action=" 123" // 这个地址不是必须的。可随便写
: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>
上传:
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!');
}
//校验成功上传文件
if(isJPG && isLt2M == true){
console.log(file);
//将文件转化为formdata数据上传
let fd = new FormData()
fd.append('file', file)
console.log(fd)
// post上传图片
let that = this
new Promise(function (resolve, reject) {
that.axios.post('/file/imgUpload', fd,
{
headers: {
'Content-Type': 'multipart/form-data'
}
}).then((response) => {
that.imgId = response.data.data
resolve(that.imgId);
}).catch((error) =>{
this.$message.error('头像上传失败,请重新上传!');
})
}).then(function (id){
that.axios.get('/file/view/'+id)
.then((response) => {
that.imageUrl = response.request.responseURL;
})
})
}
return isJPG && isLt2M;
},
更多推荐
已为社区贡献19条内容
所有评论(0)