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...">