Pseudo file upload with Javascript

Asked

Viewed 396 times

1

My intention is to make a pseudo-upload of any file, when I say pseudo I refer to the fact that: it should not go to the server.. and turn it into base64

Like, I select an X image but instead of it upada normally for the server it is transformed into Base64 on the browser side. Is it possible to do this with Javascript? What function should I use?

  • By pseudo-upload I think you mean "read", do you want to access local files using javascript? If this is the case, you use the File + HTML 5 API. Full tutorial here.

1 answer

1


If your question is only how to turn a file into Base64:

Use the function FileReader#readAsDataURL to read the file. After reading, you can use FileReader#result to obtain the result.

see browsers that support

function toBase64() {
  // obtém o arquivo
  var file = document.querySelector('input').files[0];
  // obtém uma instância de FileReader
  var fileReader = new FileReader();

  // Faz a leitura do arquivo
  if (file) {
    fileReader.readAsDataURL(file);
  }
  
  // Quando concluir a leitura, o resultado é inserido no parágrafo 'output'
  fileReader.onloadend = function() {
    document.getElementById('output').innerHTML = fileReader.result;
  };
}
<input type='file' onchange='toBase64()' />
<p id='output'></p>

On the website of Mozilla Developer Network there is a very interesting example using the result read by FileReader as an attribute value src of a img, follow:

/**
 * SRC:
 * https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
 */

function previewFile() {
  var preview = document.querySelector('img');
  var file    = document.querySelector('input[type=file]').files[0];
  var reader  = new FileReader();

  reader.onloadend = function () {
    preview.src = reader.result;
  }

  if (file) {
    reader.readAsDataURL(file);
  } else {
    preview.src = "";
  }
}
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">

Browser other questions tagged

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