vue实现修改头像
实现修改头像功能
前端部分(Vue实现)
创建文件上传组件,使用<input type="file">获取用户选择的图片文件
<template>
<div>
<img :src="avatarUrl" width="100" height="100">
<input type="file" @change="handleFileChange" accept="image/*">
<button @click="uploadAvatar">上传头像</button>
</div>
</template>
<script>
export default {
data() {
return {
avatarUrl: '默认头像URL',
selectedFile: null
}
},
methods: {
handleFileChange(event) {
this.selectedFile = event.target.files[0]
// 本地预览
const reader = new FileReader()
reader.onload = (e) => {
this.avatarUrl = e.target.result
}
reader.readAsDataURL(this.selectedFile)
},
async uploadAvatar() {
if (!this.selectedFile) return
const formData = new FormData()
formData.append('avatar', this.selectedFile)
try {
const response = await axios.post('/api/upload-avatar', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
this.avatarUrl = response.data.url
// 更新用户信息
} catch (error) {
console.error('上传失败', error)
}
}
}
}
</script>
后端部分(Node.js示例)
处理文件上传并保存到服务器
const express = require('express')
const multer = require('multer')
const path = require('path')
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/avatars')
},
filename: (req, file, cb) => {
const ext = path.extname(file.originalname)
cb(null, `${Date.now()}${ext}`)
}
})
const upload = multer({ storage })
app.post('/api/upload-avatar', upload.single('avatar'), (req, res) => {
if (!req.file) {
return res.status(400).send('没有上传文件')
}
const avatarUrl = `/avatars/${req.file.filename}`
// 这里应该更新数据库中的用户头像URL
res.json({ url: avatarUrl })
})
数据库更新
在用户模型中更新头像URL字段
// 假设使用Mongoose
User.findByIdAndUpdate(userId, { avatar: avatarUrl }, { new: true })
.then(updatedUser => {
console.log('头像更新成功')
})
.catch(err => {
console.error('更新失败', err)
})
优化建议
添加文件类型和大小验证
// 前端验证
handleFileChange(event) {
const file = event.target.files[0]
const validTypes = ['image/jpeg', 'image/png', 'image/gif']
const maxSize = 2 * 1024 * 1024 // 2MB
if (!validTypes.includes(file.type)) {
alert('请上传JPEG/PNG/GIF格式的图片')
return
}
if (file.size > maxSize) {
alert('图片大小不能超过2MB')
return
}
this.selectedFile = file
// 预览代码...
}
添加上传进度显示
<template>
<div>
<progress v-if="uploadProgress > 0" :value="uploadProgress" max="100"></progress>
</div>
</template>
<script>
// 在uploadAvatar方法中
const response = await axios.post('/api/upload-avatar', formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
onUploadProgress: progressEvent => {
this.uploadProgress = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
)
}
})
</script>






