简体   繁体   English

如何使用fs读取和保存base64图像

[英]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 api, I usually receive the base64 in the controller with "var imagem = req.body.imagem; ". 我正在创建一个api节点,在前端(它与api分开,我使用fetch发送数据)我选择一个jpg文件并以base64格式发送到api,我通常会收到base64带有“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. 我现在需要使用这个base64并将其转换为图像以保存在../../public/img目录中。 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);
    }
}

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 ). 您可以将图像从Base64表示其二进制表示的字符串转换为转换Buffer - new Buffer(b64_image, 'base64')以了解更多关于这个这个答案 )。 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). 然后,您可以使用fs.writeFile (如果您想异步保存文件)或fs.writeFileSync (如果您想同步保存文件)将缓冲区保存到本地文件系统。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM