How to read and save base64 image with fs

问题: 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...

问题:

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);
    }
}

回答1:

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);
  • 发表于 2019-01-21 16:21
  • 阅读 ( 176 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除