want to achieve the function of changing the avatar, but why do you need to refresh the page to display the changed avatar every time? you can see that the pictures in the folder used to store the avatar have been changed. if there is no refresh, the route switches out and then switches back to the previous avatar, and logging out and logging in again is the same as the previous avatar.
this is my vue.js code
<td id="yi">
<div class="touxiang" @click.stop="uploadHeadImg">
<img :src="userInfos.avatar" alt="">
</div>
<input type="file" accept="image/jpg,image/png,image/jpeg" @change="handleFile" class="hiddenInput" name="avatar" ref="avatarInput">
<a @click="dianwo"></a>
</td>
data
userInfos:{
avatar:""
}
methods
//
uploadHeadImg(){
this.$el.querySelector(".hiddenInput").click()
},
handleFile(e){
let $target = e.target || e.srcElement //
let file = $target.files[0]
var reader = new FileReader()
reader.onload = (data)=>{
let res = data.target || data.srcElement
this.userInfos.avatar = res.result
}
reader.readAsDataURL(file)
},
dianwo(){
if(this.$refs.avatarInput.files.length !== 0){
var image = new FormData()
image.append("avatar",this.$refs.avatarInput.files[0])
image.append("username",this.name)
this.$axios.post("/touxiang",image,{
headers:{
"Content-Type":"multipart/form-data"
}
})
.then((res)=>{
//console.log("")
//location.reload()
//this.$router.go(0) //
})
}
}
this is my login method to determine whether the user has changed the avatar to load the default or modified avatar
this.$axios.get("/gettouxiang/"+uname)
.then((res)=>{
if(res.list !== null){
this.userInfos.avatar = "static/assets//"+ uname + "/avatar.jpg"
}else{
//console.log("")
this.userInfos.avatar = "static/assets/2.jpg"
}
})
this is the profile picture stored by different users, this is the test user"s, and it is full of avatar.jpg
this is
in Node.js. router.post("/touxiang",function(req,res,next){
let form = new formidable.IncomingForm()
form.parse(req,function(err,fields,files){
if(err){
return next(err)
}
let username =fields.username
let extname = path.extname(files.avatar.name)
let oldpath = files.avatar.path;
let newpath = "../static/assets//"+username+"/avatar"+extname;
let avatarName = "avatar"+extname;
fs.rename(oldpath,newpath,function(error){
if(error){
console.log(error)
}
})
User.updateOne({username:username},{photo:newpath},function(err,list){
if(err){
console.log(err)
}
Touxiang.findOne({
username:username
},function(errs,docs){
if(errs){
console.log(errs)
}
if(docs == null){
new Touxiang({
username:username,
photo:avatarName
}).save(function(error,result){
if(error){
console.log(error)
}
res.json("done")
})
}else {
Touxiang.deleteOne({username:username},function(err2){
if(err2){
console.log(err2)
}
new Touxiang({
username:username,
photo:avatarName
}).save(function(error,result){
if(error){
console.log(error)
}
res.json("done")
})
})
}
})
})
})
})