Node.js storage user profile picture problem

to achieve the function of changing avatars for users, it is now possible for a user to change the avatar after selecting the avatar and clicking OK. But if the avatar of another account is still the one that has just been changed, that is to say, there is only one picture saved in that avatar. I changed the picture only by swapping that picture back and forth, without saving other images. How to store different pictures, and then log in to different accounts will have corresponding avatars.

this is my HTML code. Confirm it to the background by clicking "dianwo"

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.userInfo.avatar = res.result
                
            }
            reader.readAsDataURL(file)
        },
        dianwo(){
            if(this.$refs.avatarInput.files.length !== 0){
               // console.log(this.$refs.avatarInput.files[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(res)
                })

            }
        }
        
        

this is the background code.

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 extname = path.extname(files.avatar.name)
    let oldpath = files.avatar.path;
    let newpath = "../static/assets/avatar/avatar"+extname;
    let avatarName = "avatar"+extname;
    fs.rename(oldpath,newpath,function(error){
        if(error){
            console.log(error)
        }
    })
    new Touxiang({
       
        photo:avatarName
    }).save(function(error,result){
        if(error){
            console.log(error)
        }
       res.json("done")

    })
})

})

Schema of Touxiang has photo and created_time

Nov.19,2021

provides the following ideas: first, after uploading the picture, the image is stored on the server, and then an access path is generated, which should be unique. Make sure to update the database at the same time, that is, to maintain an one-to-one correspondence between the absolute path of the avatar and the unique identity of the user you are currently logged in to.

Menu