Base64 Multer Nodejs

Asked

Viewed 867 times

1

I used the multer in my API, I uploaded the image, all right, but I would like to use Base64, here comes the doubt (I do not know much about base64), what’s the best way to do it? I made one in a way, converted the direct image of mine API, and storage the base64 at the bank, however, that way I don’t have the image on my server.

router.post('/profile', multer({dest: "./public/uploads/"}).single('avatar'), (req, res) => {
        let fileInfo = []
        let bitmap = new Buffer(fs.readFileSync(req.file.path), 'base64')
        fileInfo.push({
            "originalName": req.file.originalName,
            "size": req.file.size,
            "base64": new Buffer(fs.readFileSync(req.file.path)).toString("base64")
        })

        fs.unlink(req.file.path)

        let query = "UPDATE ?? SET ?? = ? WHERE ?? = ?"
        let table = ["users_info", "avatar", fileInfo[0].base64, "id_user", req.body.id]
        query = mysql.format(query, table)
        connection.query(query, (err, rows) => {
            if(err){
                res.json({"Error": true, "Message": "Erro ao executar query do Mysql"});
            }else{
                res.json({"Error": false, "Message": "Successo", "base64": fileInfo[0].base64});
            }
        })
    }) 

So, I remembered, when I uploaded (uploaded from the app), I sent Base64 already, so my question is, what’s the best way to do this? and I want to store the images on my server.

  • Do you want to store the images on the server as files instead of storing in the database as Base64? In this case, simply replace the field where you save the image with a field where you would save the image path and save the image in an uploads directory.

1 answer

0


After a while, I managed to solve my problem, I leave here the solution for case, someone goes through the same problem.

router.post('/avatar', upload.single('avatar'), (req, res, next) => {
    let base64Data = req.body.base64
    let newName    = req.body.avatar
    fs.writeFile("public/images/" + newName, base64Data, 'base64', (err, data) => {
        if(err){
            return res.json({"Error": true, "Message": "Erro ao fazer upload de imagem"})   
        }else{
            let query = "UPDATE ?? SET ?? = ? WHERE ?? = ?"
            let table = ["users_info", "avatar", newName, "id_user", req.body.id]
            query = mysql.format(query, table)
            pool.query(query, (err, rows) => {
                if(err){
                    return res.json({"Error": true, "Message": "Erro ao executar query do Mysql"})
                }
                return res.json({"Error": false, "Message": "Successo", "avatar": url + 'images/' + newName})
            })
        }
    })
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.