自定義上傳
<el-upload class="avatar-uploader" action="https://www.baidu.com/"
:limit="1"
:show-file-list="false"
:with-credentials="true"
:http-request="imgUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<el-button size="small" type="primary" style="margin: 0 1rem;" @click="uploadAvatar">上傳</el-button>
<script>
imgUpload(val) {
logout(val.file)
console.log(val.file)
this.imageUrl = URL.createObjectURL(val.file.raw);
this.file = val.file
},
uploadAvatar() {
let file = this.file
let params = new FormData() //創建form對象
params.append('file', file) //通過append向form對象添加數據
// console.log(params.get('uploadFile')) //FormData私有類對象,訪問不到,可以通過get判斷值是否傳進去
identityUpdateAvatar(params).then(res => {
console.log(res)
if (res)
message({message: '修改成功', type: 'success', this: this})
})
}
</script>
默認上傳
<el-upload
class="avatar-uploader"
action="http://****:9999/api.file/post"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:with-credentials="true"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<script>
handleAvatarSuccess(res, file) {
this.imageUrl = URL.createObjectURL(file.raw);
identityDetail(this.userInfo.id).then(res => {
message({message: '上傳成功,頭像以更改', type: 'success', this: this})
localStorage.setItem('userInfo', JSON.stringify(res.data)) // 更新本地用戶信息
this.$store.commit('userInfomu', res.data) // 以荷載的方式調用該方法
this.userInfo = res.data
let t;
t = setInterval(() => {
this.imageUrl = ''
clearInterval(t)
}, 1500)
})
},
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isPNG = file.type === 'image/png';
const isLt5M = file.size / 1024 / 1024 < 5;
if (isJPG || isPNG) {
if (isLt5M) {
return true
} else {
this.$message.error('上傳頭像圖片大小不能超過 5MB!');
return false
}
} else {
this.$message.error('上傳頭像圖片只能是 JPG 格式!');
return false
}
}
</script>