Base64 Multer NodeJS

1

I used multer in my API, I uploaded the image, all right, but I would like to use base64, then I enter the doubt (I do not know much about base64 ), what better way to do it? I made one in a way, I converted the image straight from my API , and I store base64 in the database, however, that way I do not 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 that when I uploaded (uploaded the app), I would send in base64 already, so my question is, what is the best way to do it? and I want to store the images on my server.

    
asked by anonymous 11.09.2017 / 22:30

1 answer

0

After a while, I managed to solve my problem, I leave here the solution in case someone has 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})
            })
        }
    })
})
    
26.09.2017 / 17:53