Using input file with JS

Asked

Viewed 1,177 times

1

Good afternoon everyone, I am creating a registration screen and I have a question regarding <input type="file"> (This file will be 100% of the cases an image, without validation). I would like to register and pass the same to another screen, using only JS, but I don’t quite understand how I can save this image in a JSON, since I could only do this if it was a URL (right? ). Does anyone have any hint of what I can do?

  • Related https://answall.com/questions/338010, it may even be what you want

1 answer

1


You have to buffer this image.

Inputs of the type file only captures file metadata (including the URI you see in value). The (binary) file itself is only read completely when you send it through a submit, or you can use Javascript to obtain such data.

With Javascript you can use the class FileReader to read that file. In the example below, the binary value of the file is converted to Base64, to ease the amount of load that will need to be transmitted, basically a compression.

const meuImput = document.getElementById('id_do_input');
const reader = new FileReader();
reader.readAsDataURL(meuImput.files[0]);
reader.onload = function () {
  // Aqui temos a sua imagem convertida em string em base64.
  console.log(reader.result);
};
  • Got it! And then in case I unpack like I would?

  • 1

    If you are unpacking in the back end, it will depend on the language. If you are unpacking on the front... it probably won’t be necessary. You can use the string as src of a img, in Base64 even, and will work normally.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.