简体   繁体   中英

Image to Base64 with NodeJS (Express)

I'm doing a test, and I need to convert an image to base64 to store in my DB

forget about DB, I just need the base64 as a string.

This is my form:

<form action="/cadastrado" method="POST">
   <! -- other irrelevants inputs -->
   <input type="file" name="input_file" id="input_file" onchange="converterParaBase64()" required><br>
   <button type="submit" onclick="base64()">CADASTRAR</button>
</form>

This is my route after submit the form:

app.post("/cadastrado", (req, res) => {
    const {input_nome, input_telefone, input_cpf, input_email, input_file} = req.body;

    console.log(req);

    return res.json({
      nome: input_nome,
      telefone: input_telefone,
      cpf: input_cpf,
      email: input_email,
      // base64image: input_file.toBase64 (I need something like this)
    });
  });

I'm doing greate about using the strings inputs, like nome, telefone, cpf and email (variables in PT-BR)

But I can't say the same with input_file

When I console.log(req.body) i get this:

{
  input_nome: '1',
  input_telefone: '2',
  input_cpf: '3',
  input_email: '4',
  input_file: 'levia.jpg'
}

I need to convert this levia.png image into base64 as a string.

How I can do it?

UPDATE 1: Seems like the image in json, is just the file name. It is possible to convert in client-side and after send to server-side?

Try this

var fs = require('fs');

app.post("/cadastrado", (req, res) => {
    const {input_nome, input_telefone, input_cpf, input_email, input_file} = req.body;

    console.log(req);

var bitmap = fs.readFileSync(input_file);
var base64File = new Buffer(bitmap).toString('base64');

    return res.json({
      nome: input_nome,
      telefone: input_telefone,
      cpf: input_cpf,
      email: input_email,
      base64image: base64File 
    });
  });

so I figured out how to resolve my problem.

Kind of vicarious what I did. I don't know if in future this can result in a problem, so I want to share with you.

Basically I create a input and edit his value in client side. Of course, I don't want a big input with a Base64 code messing with my poor HTML, so I styled with display: none . This input is inside the form, and it is sent to my req.body .

Snippets

index.html page with form:

...
<input type="file" id="input_file" name="input_file" onchange="convBase64()" required />
...

script.js with some logic

...
document.getElementById('input_base64').value = `${stringBase64}`;
...

css to hide the input with encoded image:

#input_base64 {

display: none;

}

This invisible input is inside the form. When the form is submitted, the input value is sent to body of request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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