2

I am creating an api node that on the front end (it is separate from the api, I am using fetch to send the data) I am selecting a jpg file and sending in base64 form to the api, I usually receive the base64 in the controller with "var imagem = req.body.imagem; ". I need now to take this base64 and turn it into an image to save in the ../../public/img directory. How could I do that?

const mongoose = require('mongoose');
const Cup = require('../models/Cup');
module.exports = {
    //listagem
    async index(req, res) {
        const cups = await Cup.find();

        return res.json(cups);
    },
    //criaçao
    async store(req, res) {
        var nome = req.body.nome;
        var caminho = req.body.caminho;
        var tema = req.body.tema;
        var imagem = req.body.imagem;
        const cup = await Cup.create({
            nome: nome,
            caminho: caminho,
            tema: tema
        });
        return res.json(cup);
    }
}
Henrique Ramos
  • 714
  • 8
  • 25

1 Answers1

4

You can convert an image from a base64 representation to its binary representation by converting the string to a Buffer - new Buffer(b64_image, 'base64') (read more on this in this answer). You can then save the buffer to the local filesystem using either fs.writeFile (in case you'd like to save the file asynchronously) or fs.writeFileSync (in case you'd like to save the file synchronously).

What you're trying to do could be accomplished with something like this:

const fs = require("fs");

const base64Image = "BASE_64_IMAGE";
const imageBuffer = new Buffer(base64Image, "base64");

fs.writeFileSync("image.png", imageBuffer);
Itai Steinherz
  • 777
  • 1
  • 9
  • 19
  • I replied with [atob()/btoa()](https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding) (which are great for base64 encoding/decoding "most of the time") ... but your answer is much better :) – paulsm4 Jan 19 '19 at 20:35
  • @paulsm4 Thanks :) `atob()` could also work well, but when running using Node.js it's usually better to use native `Buffer` objects. – Itai Steinherz Jan 19 '19 at 20:38
  • I got a look and I got to that code: "fs.writeFile ('message.txt', 'Hello Node.js', 'utf8', callback); how and where would I insert my base64? – Henrique Ramos Jan 19 '19 at 20:38
  • @HenriqueRamos In the code you mentioned, `'Hello Node.js'` is the data that's being saved to `message.txt` (and not the image buffer). In your case, the code used to save the file should be along the lines of: `fs.writeFile ('image.png', imageBuffer, callback);`. – Itai Steinherz Jan 19 '19 at 20:41
  • @ItaiSteinherz I managed to make a txt file be created, but I still do not understand the buffer well, first that instead of message.txt it has to be correct image.jpg? But regarding base64 and the buffer I did not quite understand – Henrique Ramos Jan 19 '19 at 20:49
  • @HenriqueRamos You have to give the buffer to `fs.writeFile` as the data it should write to the file. I'll add a code example to my answer. – Itai Steinherz Jan 19 '19 at 20:50
  • @ItaiSteinherz I did the following: var imagem = req.body.imagem; const base64Image = imagem; const imageBuffer = new Buffer (base64Image, "base64"); fs.writeFileSync ('./ public/img/message.jpg', imageBuffer); but when I try to open the image to visualize this warning appears: there is no support for this file format – Henrique Ramos Jan 19 '19 at 21:01
  • @HenriqueRamos Check out [this answer](https://stackoverflow.com/a/43488020/91555510). The issue may be caused by how the given base64 image (`req.body.imagem`) is formatted. – Itai Steinherz Jan 19 '19 at 21:06
  • @ItaiSteinherz That worked! Thanks for your patience. – Henrique Ramos Jan 19 '19 at 21:10
  • @HenriqueRamos You're welcome :) Feel free to mark my answer as approved ;) – Itai Steinherz Jan 19 '19 at 21:14