Pseudo upload file with JavaScript

1

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

Type, I select an X image but instead of it being upada normally to the server it is turned into base64 on the browser side. is it possible to do this with Javascript? What function should I use?

    
asked by anonymous 19.04.2015 / 04:05

1 answer

1

If your question is just how to transform a file into base64:

Use the FileReader#readAsDataURL function to read the file. Once read, you can use FileReader#result to get the result.

view 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 Mozilla Developer Network site there is a good example interesting that uses the result read by FileReader as value of attribute src of a img , follows:

/**
 * 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...">
    
19.04.2015 / 14:31