从服务器到客户端检索图像(Mongodb,React js,Node js)

2cmtqfgy  于 2023-04-11  发布在  Go
关注(0)|答案(1)|浏览(129)

我正在使用mongoose存储用户的信息。(下面是Node js中代码的快速摘要)

const UserSchema = new mongoose.Schema({
    
    username: {
        type: String,
        required: true,
        lowercase: true,
        validate: validateUsername
    },

    password: {
        type: String,
        required: true,
        validate: validatePassword
    },

    image: {
        type: Buffer,
        required: false,
    },

我使用fs模块将图像存储为Buffer。(这是用户的默认配置文件图片)

const imagePath = './src/images/user.png'
const imageName = 'profile_pic'
const imageBuffer = fs.readFileSync(imagePath)

const user = new User({ username: username. password: password, image: imageBuffer})

最后,我将发送一个对象,其中包含用户信息以及访问令牌和刷新令牌。

const new_user = {
                username: user.username,
                image: user.image,
                email: user.email,
                team: user.team,
                createdAt: user.createdAt,
                refreshToken: user.refreshToken,
                refreshTokenExpirationL : user.refreshTokenExpiration
            }
            
            const accessToken = jwt.sign(new_user, process.env.ACCESS_SECRET_TOKEN)
            const refreshToken = jwt.sign(new_user, process.env.REFRESH_SECRET_TOKEN)
    
            console.log("Logged in")
            res.status(200).send({accessToken: accessToken, refreshToken: refreshToken, user: new_user})

该信息应该由客户端存储为cookie。
但是,由于图像缓冲区项总是太大,因此无法保存cookie。
所以我的问题是,存储和检索图像的最佳方法是什么?使用mongodb,node js和react js。
我目前的方式是否有效,或者我应该探索另一种选择?例如,我可以尝试将其保存在其他地方并使用链接检索图像?我希望尽可能将事情保持在本地,但我愿意接受建议

webghufk

webghufk1#

通常我们不把图片作为缓冲存储在数据库中,最好的方法是把图片存储在服务器中,把url存储在数据库中,然后使用它们。
这种方式有助于解决很多问题,
1.您可以缓存图像以便在第一次加载后快速提供,
1.你的API响应会太小,那么它会很快收到。
1.你的图像可以在你的数据加载后自由加载。
1.这也将给予用户更好的体验。
因此,我的建议是将图像存储在文件服务器中,并将链接存储在数据库中。

相关问题