UPD TypeScript version is also available in answers
Now I'm getting File object by this line:
file = document.querySelector('#files > input[type="file"]').files[0]
I need to send this file via json in base 64. What should I do to convert it to base64 string?
Try the solution using the FileReader class:
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
var file = document.querySelector('#files > input[type="file"]').files[0];
getBase64(file); // prints the base64 string
Notice that .files[0] is a File type, which is a sublcass of Blob. Thus it can be used with FileReader.
See the complete working example.
Modern ES6 way (async/await)
const toBase64 = file => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
async function Main() {
const file = document.querySelector('#myfile').files[0];
console.log(await toBase64(file));
}
Main();
UPD:
If you want to catch errors
async function Main() {
const file = document.querySelector('#myfile').files[0];
try {
const result = await toBase64(file);
return result
} catch(error) {
console.error(error);
return;
}
//...
}
If you're after a promise-based solution, this is #Dmitri's code adapted for that:
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
var file = document.querySelector('#files > input[type="file"]').files[0];
getBase64(file).then(
data => console.log(data)
);
Building up on Dmitri Pavlutin and joshua.paling answers, here's an extended version that extracts the base64 content (removes the metadata at the beginning) and also ensures padding is done correctly.
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
let encoded = reader.result.toString().replace(/^data:(.*,)?/, '');
if ((encoded.length % 4) > 0) {
encoded += '='.repeat(4 - (encoded.length % 4));
}
resolve(encoded);
};
reader.onerror = error => reject(error);
});
}
TypeScript version
const file2Base64 = (file:File):Promise<string> => {
return new Promise<string> ((resolve,reject)=> {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result?.toString() || '');
reader.onerror = error => reject(error);
})
}
JavaScript btoa() function can be used to convert data into base64 encoded string
<div>
<div>
<label for="filePicker">Choose or drag a file:</label><br>
<input type="file" id="filePicker">
</div>
<br>
<div>
<h1>Base64 encoded version</h1>
<textarea id="base64textarea"
placeholder="Base64 will appear here"
cols="50" rows="15"></textarea>
</div>
</div>
var handleFileSelect = function(evt) {
var files = evt.target.files;
var file = files[0];
if (files && file) {
var reader = new FileReader();
reader.onload = function(readerEvt) {
var binaryString = readerEvt.target.result;
document.getElementById("base64textarea").value = btoa(binaryString);
};
reader.readAsBinaryString(file);
}
};
if (window.File && window.FileReader && window.FileList && window.Blob) {
document.getElementById('filePicker')
.addEventListener('change', handleFileSelect, false);
} else {
alert('The File APIs are not fully supported in this browser.');
}
Here are a couple functions I wrote to get a file in a json format which can be passed around easily:
//takes an array of JavaScript File objects
function getFiles(files) {
return Promise.all(files.map(getFile));
}
//take a single JavaScript File object
function getFile(file) {
const reader = new FileReader();
return new Promise((resolve, reject) => {
reader.onerror = () => { reader.abort(); reject(new Error("Error parsing file"));}
reader.onload = function () {
//This will result in an array that will be recognized by C#.NET WebApi as a byte[]
let bytes = Array.from(new Uint8Array(this.result));
//if you want the base64encoded file you would use the below line:
let base64StringFile = btoa(bytes.map((item) => String.fromCharCode(item)).join(""));
//Resolve the promise with your custom file structure
resolve({
bytes,
base64StringFile,
fileName: file.name,
fileType: file.type
});
}
reader.readAsArrayBuffer(file);
});
}
//using the functions with your file:
file = document.querySelector('#files > input[type="file"]').files[0]
getFile(file).then((customJsonFile) => {
//customJsonFile is your newly constructed file.
console.log(customJsonFile);
});
//if you are in an environment where async/await is supported
files = document.querySelector('#files > input[type="file"]').files
let customJsonFiles = await getFiles(files);
//customJsonFiles is an array of your custom files
console.log(customJsonFiles);
const fileInput = document.querySelector('input');
fileInput.addEventListener('change', (e) => {
// get a reference to the file
const file = e.target.files[0];
// encode the file using the FileReader API
const reader = new FileReader();
reader.onloadend = () => {
// use a regex to remove data url part
const base64String = reader.result
.replace('data:', '')
.replace(/^.+,/, '');
// log to console
// logs wL2dvYWwgbW9yZ...
console.log(base64String);
};
reader.readAsDataURL(file);});
onInputChange(evt) {
var tgt = evt.target || window.event.srcElement,
files = tgt.files;
if (FileReader && files && files.length) {
var fr = new FileReader();
fr.onload = function () {
var base64 = fr.result;
debugger;
}
fr.readAsDataURL(files[0]);
}
}
I have used this simple method and it's worked successfully
function uploadImage(e) {
var file = e.target.files[0];
let reader = new FileReader();
reader.onload = (e) => {
let image = e.target.result;
console.log(image);
};
reader.readAsDataURL(file);
}
Convert any file to base64 using this way -
_fileToBase64(file: File) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result.toString().substr(reader.result.toString().indexOf(',') + 1));
reader.onerror = error => reject(error);
});
}
This works
// fileObj: File
const base64 = window.URL.createObjectURL(fileObj);
// You can use it with <img src={base64} />
This page is the first match when searching for how to convert a file object to a string. If you are not concerned about base64, the answer to that questions is as simple as:
str = await file.text()
Extending on the above solutions by adding, with a use case where I required
the ability to iterate through multiple fields on a form and get their values
and with one being a file, it caused problems with he async requirements
Solved it like this:
async collectFormData() {
// Create the file parsing promise
const toBase64 = file => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
let form_vals = []
let els = [] // Form elements collection
// This is separate because wrapping the await in a callback
// doesn't work
$(`.form-field`).each(function (e) {
els.push(this) // add to the collection of form fields
})
// Loop through the fields to collect information
for (let elKey in els) {
let el = els[elKey]
// If the field is input of type file. call the base64 parser
if ($(el).attr('type') == 'file') {
// Get a reference to the file
const file = el.files[0];
form_vals.push({
"key": el.id,
"value": await toBase64(file)
})
}
// TODO: The rest of your code here form_vals will now be
// populated in time for a server post
}
This is purely to solve the problem of dealing with multiple fields
in a smoother way
Related
I am using the following script for reading image data as base64 url.
function getBase64(incomingfile) {
var reader = new FileReader;
reader.readAsDataURL(incomingfile);
reader.onloadend = ()=>{
console.log(reader.result);
}
}
This is working fine and printing the result on console. But when I try to apply this below code
function getBase64(incomingfile) {
var reader = new FileReader;
reader.readAsDataURL(incomingfile);
reader.onloadend = ()=>{
return reader.result;
}
}
I am not getting the result of this function after calling. What should I do to get return value of Filereader.
the file The FileReader methods work asynchronously but don't return a Promise so when attempting to retrieve the result immediately after calling a method will not work
try this
let logBase64 = "";
function getBase64(incomingfile) {
var reader = new FileReader();
reader.readAsDataURL(incomingfile);
return new Promise((resolve, reject) => {
reader.onloadend = () => {
resolve(reader.result);
};
}).then((result) => {
logBase64 = result;
console.log(logBase64);
});
}
UPD TypeScript version is also available in answers
Now I'm getting File object by this line:
file = document.querySelector('#files > input[type="file"]').files[0]
I need to send this file via json in base 64. What should I do to convert it to base64 string?
Try the solution using the FileReader class:
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
var file = document.querySelector('#files > input[type="file"]').files[0];
getBase64(file); // prints the base64 string
Notice that .files[0] is a File type, which is a sublcass of Blob. Thus it can be used with FileReader.
See the complete working example.
Modern ES6 way (async/await)
const toBase64 = file => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
async function Main() {
const file = document.querySelector('#myfile').files[0];
console.log(await toBase64(file));
}
Main();
UPD:
If you want to catch errors
async function Main() {
const file = document.querySelector('#myfile').files[0];
try {
const result = await toBase64(file);
return result
} catch(error) {
console.error(error);
return;
}
//...
}
If you're after a promise-based solution, this is #Dmitri's code adapted for that:
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
var file = document.querySelector('#files > input[type="file"]').files[0];
getBase64(file).then(
data => console.log(data)
);
Building up on Dmitri Pavlutin and joshua.paling answers, here's an extended version that extracts the base64 content (removes the metadata at the beginning) and also ensures padding is done correctly.
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
let encoded = reader.result.toString().replace(/^data:(.*,)?/, '');
if ((encoded.length % 4) > 0) {
encoded += '='.repeat(4 - (encoded.length % 4));
}
resolve(encoded);
};
reader.onerror = error => reject(error);
});
}
TypeScript version
const file2Base64 = (file:File):Promise<string> => {
return new Promise<string> ((resolve,reject)=> {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result?.toString() || '');
reader.onerror = error => reject(error);
})
}
JavaScript btoa() function can be used to convert data into base64 encoded string
<div>
<div>
<label for="filePicker">Choose or drag a file:</label><br>
<input type="file" id="filePicker">
</div>
<br>
<div>
<h1>Base64 encoded version</h1>
<textarea id="base64textarea"
placeholder="Base64 will appear here"
cols="50" rows="15"></textarea>
</div>
</div>
var handleFileSelect = function(evt) {
var files = evt.target.files;
var file = files[0];
if (files && file) {
var reader = new FileReader();
reader.onload = function(readerEvt) {
var binaryString = readerEvt.target.result;
document.getElementById("base64textarea").value = btoa(binaryString);
};
reader.readAsBinaryString(file);
}
};
if (window.File && window.FileReader && window.FileList && window.Blob) {
document.getElementById('filePicker')
.addEventListener('change', handleFileSelect, false);
} else {
alert('The File APIs are not fully supported in this browser.');
}
Here are a couple functions I wrote to get a file in a json format which can be passed around easily:
//takes an array of JavaScript File objects
function getFiles(files) {
return Promise.all(files.map(getFile));
}
//take a single JavaScript File object
function getFile(file) {
const reader = new FileReader();
return new Promise((resolve, reject) => {
reader.onerror = () => { reader.abort(); reject(new Error("Error parsing file"));}
reader.onload = function () {
//This will result in an array that will be recognized by C#.NET WebApi as a byte[]
let bytes = Array.from(new Uint8Array(this.result));
//if you want the base64encoded file you would use the below line:
let base64StringFile = btoa(bytes.map((item) => String.fromCharCode(item)).join(""));
//Resolve the promise with your custom file structure
resolve({
bytes,
base64StringFile,
fileName: file.name,
fileType: file.type
});
}
reader.readAsArrayBuffer(file);
});
}
//using the functions with your file:
file = document.querySelector('#files > input[type="file"]').files[0]
getFile(file).then((customJsonFile) => {
//customJsonFile is your newly constructed file.
console.log(customJsonFile);
});
//if you are in an environment where async/await is supported
files = document.querySelector('#files > input[type="file"]').files
let customJsonFiles = await getFiles(files);
//customJsonFiles is an array of your custom files
console.log(customJsonFiles);
const fileInput = document.querySelector('input');
fileInput.addEventListener('change', (e) => {
// get a reference to the file
const file = e.target.files[0];
// encode the file using the FileReader API
const reader = new FileReader();
reader.onloadend = () => {
// use a regex to remove data url part
const base64String = reader.result
.replace('data:', '')
.replace(/^.+,/, '');
// log to console
// logs wL2dvYWwgbW9yZ...
console.log(base64String);
};
reader.readAsDataURL(file);});
onInputChange(evt) {
var tgt = evt.target || window.event.srcElement,
files = tgt.files;
if (FileReader && files && files.length) {
var fr = new FileReader();
fr.onload = function () {
var base64 = fr.result;
debugger;
}
fr.readAsDataURL(files[0]);
}
}
I have used this simple method and it's worked successfully
function uploadImage(e) {
var file = e.target.files[0];
let reader = new FileReader();
reader.onload = (e) => {
let image = e.target.result;
console.log(image);
};
reader.readAsDataURL(file);
}
Convert any file to base64 using this way -
_fileToBase64(file: File) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result.toString().substr(reader.result.toString().indexOf(',') + 1));
reader.onerror = error => reject(error);
});
}
This works
// fileObj: File
const base64 = window.URL.createObjectURL(fileObj);
// You can use it with <img src={base64} />
This page is the first match when searching for how to convert a file object to a string. If you are not concerned about base64, the answer to that questions is as simple as:
str = await file.text()
Extending on the above solutions by adding, with a use case where I required
the ability to iterate through multiple fields on a form and get their values
and with one being a file, it caused problems with he async requirements
Solved it like this:
async collectFormData() {
// Create the file parsing promise
const toBase64 = file => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
let form_vals = []
let els = [] // Form elements collection
// This is separate because wrapping the await in a callback
// doesn't work
$(`.form-field`).each(function (e) {
els.push(this) // add to the collection of form fields
})
// Loop through the fields to collect information
for (let elKey in els) {
let el = els[elKey]
// If the field is input of type file. call the base64 parser
if ($(el).attr('type') == 'file') {
// Get a reference to the file
const file = el.files[0];
form_vals.push({
"key": el.id,
"value": await toBase64(file)
})
}
// TODO: The rest of your code here form_vals will now be
// populated in time for a server post
}
This is purely to solve the problem of dealing with multiple fields
in a smoother way
I need to convert my image to a Base64 string so that I can send my image to a server.
Is there any JavaScript file for this? Else, how can I convert it?
There are multiple approaches you can choose from:
1. Approach: FileReader
Load the image as blob via XMLHttpRequest and use the FileReader API (readAsDataURL()) to convert it to a dataURL:
function toDataURL(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0', function(dataUrl) {
console.log('RESULT:', dataUrl)
})
This code example could also be implemented using the WHATWG fetch API:
const toDataURL = url => fetch(url)
.then(response => response.blob())
.then(blob => new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onloadend = () => resolve(reader.result)
reader.onerror = reject
reader.readAsDataURL(blob)
}))
toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0')
.then(dataUrl => {
console.log('RESULT:', dataUrl)
})
These approaches:
have better compression
work for other file types as well
Browser Support:
http://caniuse.com/#feat=filereader
http://caniuse.com/#feat=fetch
2. Approach: Canvas (for legacy browsers)
Load the image into an Image-Object, paint it to a nontainted canvas and convert the canvas back to a dataURL.
function toDataURL(src, callback, outputFormat) {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function() {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.naturalHeight;
canvas.width = this.naturalWidth;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
};
img.src = src;
if (img.complete || img.complete === undefined) {
img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
img.src = src;
}
}
toDataURL(
'https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0',
function(dataUrl) {
console.log('RESULT:', dataUrl)
}
)
In detail
Supported input formats:
image/png, image/jpeg, image/jpg, image/gif, image/bmp, image/tiff, image/x-icon, image/svg+xml, image/webp, image/xxx
Supported output formats:
image/png, image/jpeg, image/webp(chrome)
Browser Support:
http://caniuse.com/#feat=canvas
Internet Explorer 10 (Internet Explorer 10 just works with same origin images)
3. Approach: Images from the local file system
If you want to convert images from the users file system you need to take a different approach.
Use the FileReader API:
function encodeImageFileAsURL(element) {
var file = element.files[0];
var reader = new FileReader();
reader.onloadend = function() {
console.log('RESULT', reader.result)
}
reader.readAsDataURL(file);
}
<input type="file" onchange="encodeImageFileAsURL(this)" />
You can use the HTML5 <canvas> for it:
Create a canvas, load your image into it and then use toDataURL() to get the Base64 representation (actually, it's a data: URL, but it contains the Base64-encoded image).
This snippet can convert your string, image and even video file to Base64 string data.
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />
<div id="imgTest"></div>
<script type='text/javascript'>
function encodeImageFileAsURL() {
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("imgTest").innerHTML = newImage.outerHTML;
alert("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
console.log("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
}
fileReader.readAsDataURL(fileToLoad);
}
}
</script>
Basically, if your image is
<img id='Img1' src='someurl'>
then you can convert it like
var c = document.createElement('canvas');
var img = document.getElementById('Img1');
c.height = img.naturalHeight;
c.width = img.naturalWidth;
var ctx = c.getContext('2d');
ctx.drawImage(img, 0, 0, c.width, c.height);
var base64String = c.toDataURL();
Here is what I did:
// Author James Harrington 2014
function base64(file, callback){
var coolFile = {};
function readerOnload(e){
var base64 = btoa(e.target.result);
coolFile.base64 = base64;
callback(coolFile)
};
var reader = new FileReader();
reader.onload = readerOnload;
var file = file[0].files[0];
coolFile.filetype = file.type;
coolFile.size = file.size;
coolFile.filename = file.name;
reader.readAsBinaryString(file);
}
And here is how you use it
base64( $('input[type="file"]'), function(data){
console.log(data.base64)
})
I found that the safest and reliable way to do it is to use FileReader().
Demo: Image to Base64
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<input id="myinput" type="file" onchange="encode();" />
<div id="dummy">
</div>
<div>
<textarea style="width:100%;height:500px;" id="txt">
</textarea>
</div>
<script>
function encode() {
var selectedfile = document.getElementById("myinput").files;
if (selectedfile.length > 0) {
var imageFile = selectedfile[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result;
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("dummy").innerHTML = newImage.outerHTML;
document.getElementById("txt").value = document.getElementById("dummy").innerHTML;
}
fileReader.readAsDataURL(imageFile);
}
}
</script>
</body>
</html>
UPDATE - THE SAME CODE WITH COMMENTS FOR #AnniekJ REQUEST:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<input id="myinput" type="file" onchange="encode();" />
<div id="dummy">
</div>
<div>
<textarea style="width:100%;height:500px;" id="txt">
</textarea>
</div>
<script>
function encode() {
// Get the file objects that was selected by the user from myinput - a file picker control
var selectedfile = document.getElementById("myinput").files;
// Check that the user actually selected file/s from the "file picker" control
// Note - selectedfile is an array, hence we check it`s length, when length of the array
// is bigger than 0 than it means the array containes file objects
if (selectedfile.length > 0) {
// Set the first file object inside the array to this variable
// Note: if multiple files are selected we can itterate on all of the selectedfile array using a for loop - BUT in order to not make this example complicated we only take the first file object that was selected
var imageFile = selectedfile[0];
// Set a filereader object to asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.
var fileReader = new FileReader();
// We declare an event of the fileReader class (onload event) and we register an anonimous function that will be executed when the event is raised. it is "trick" we preapare in order for the onload event to be raised after the last line of this code will be executed (fileReader.readAsDataURL(imageFile);) - please read about events in javascript if you are not familiar with "Events"
fileReader.onload = function(fileLoadedEvent) {
// AT THIS STAGE THE EVENT WAS RAISED
// Here we are getting the file contents - basiccaly the base64 mapping
var srcData = fileLoadedEvent.target.result;
// We create an image html element dinamically in order to display the image
var newImage = document.createElement('img');
// We set the source of the image we created
newImage.src = srcData;
// ANOTHER TRICK TO EXTRACT THE BASE64 STRING
// We set the outer html of the new image to the div element
document.getElementById("dummy").innerHTML = newImage.outerHTML;
// Then we take the inner html of the div and we have the base64 string
document.getElementById("txt").value = document.getElementById("dummy").innerHTML;
}
// This line will raise the fileReader.onload event - note we are passing the file object here as an argument to the function of the event
fileReader.readAsDataURL(imageFile);
}
}
</script>
</body>
</html>
If you have a file object, this simple function will work:
function getBase64 (file, callback) {
const reader = new FileReader();
reader.addEventListener('load', () => callback(reader.result));
reader.readAsDataURL(file);
}
Usage example:
getBase64(fileObjectFromInput, function(base64Data){
console.log("Base64 of file is", base64Data); // Here you can have your code which uses Base64 for its operation, // file to Base64 by oneshubh
});
I ended up using a function that returns a Promise.
const getImg64 = async() => {
const convertImgToBase64URL = (url) => {
console.log(url)
return new Promise((resolve, reject) => {
const img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = () => {
let canvas = document.createElement('CANVAS')
const ctx = canvas.getContext('2d')
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0);
const dataURL = canvas.toDataURL();
canvas = null;
resolve(dataURL)
}
img.src = url;
})
}
//for the demonstration purposes I used proxy server to avoid cross origin error
const proxyUrl = 'https://cors-anywhere.herokuapp.com/'
const image = await convertImgToBase64URL(proxyUrl+'https://image.shutterstock.com/image-vector/vector-line-icon-hello-wave-260nw-1521867944.jpg')
console.log(image)
}
getImg64()
You can use this approach in any async function. Then you can just await for the converted image and continue with instructions.
uploadProfile(e) {
let file = e.target.files[0];
let reader = new FileReader();
reader.onloadend = function() {
console.log('RESULT', reader.result)
}
reader.readAsDataURL(file);
}
Here is the way you can do with Javascript Promise.
const getBase64 = (file) => new Promise(function (resolve, reject) {
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result)
reader.onerror = (error) => reject('Error: ', error);
})
Now, use it in event handler.
const _changeImg = (e) => {
const file = e.target.files[0];
let encoded;
getBase64(file)
.then((result) => {
encoded = result;
})
.catch(e => console.log(e))
}
You could use FileAPI, but it's pretty much unsupported.
As far as I know, an image can be converted into a Base64 string either by FileReader() or storing it in the canvas element and then use toDataURL() to get the image. I had the similar kind of problem you can refer this.
Convert an image to canvas that is already loaded
Try this code:
For a file upload change event, call this function:
$("#fileproof").on('change', function () {
readImage($(this)).done(function (base64Data) { $('#<%=hfimgbs64.ClientID%>').val(base64Data); });
});
function readImage(inputElement) {
var deferred = $.Deferred();
var files = inputElement.get(0).files;
if (files && files[0]) {
var fr = new FileReader();
fr.onload = function (e) {
deferred.resolve(e.target.result);
};
fr.readAsDataURL(files[0]);
} else {
deferred.resolve(undefined);
}
return deferred.promise();
}
Store Base64 data in hidden filed to use.
document.querySelector('input').onchange = e => {
const fr = new FileReader()
fr.onloadend = () => document.write(fr.result)
fr.readAsDataURL(e.target.files[0])
}
<input type="file">
Needed to leverage reader to convert blob to base64, prefer to use async-await syntax so I chose to extract reader logic into helper like this:
//* Convert resBlob to base64
export const blobToData = (blob: Blob) => {
return new Promise((resolve) => {
const reader = new FileReader()
reader.onloadend = () => resolve(reader.result)
reader.readAsDataURL(blob)
})
}
and calling it using await in main code:
//* Convert resBlob to dataUrl and resolve
const resData = await blobToData(resBlob)
In the case you are facing cors origin error, there is a simple proxy called cors-fix that loads the image on server and return it as buffer array.
Therefore, we can use fetch to get the image data and filereader to convert it to dataUrl, as described by #HaNdTriX.
function toDataUrl(url) {
fetch(`https://cors-fix.web.app/v1?url=${url}`)
.then(data => data.blob().then(blob => {
const reader = new FileReader();
reader.onloadend = () => {
console.log(reader.result);
};
reader.onerror = () => {
console.log('reader error');
};
reader.readAsDataURL(blob);
}));
}
Well, if you are using Dojo Toolkit, it gives us a direct way to encode or decode into Base64.
Try this:
To encode an array of bytes using dojox.encoding.base64:
var str = dojox.encoding.base64.encode(myByteArray);
To decode a Base64-encoded string:
var bytes = dojox.encoding.base64.decode(str);
You can also simply extract base-64 only part of the URL by ding this:
var Base64URL = canvas.toDataURL('image/webp')
var Base64 = Base64URL.split(",")[1] //Returns the base64 part
Assuming that you are doing this in a browser:
With await:
import axios from 'axios'
const response = await axios.get(url, { responseType: 'blob' });
return window.URL.createObjectURL(response.data);
With promise
import axios from 'axios'
const response = await axios.get(url, { responseType: 'blob' })
.then((response) => {
const dataUrl = window.URL.createObjectURL(response.data);
// do something with your url
});
This is very simple.
1> Just call the function and pass your image.
2> Save the return value and use wherever required.
//call like this
const convertedFile = await imageToBase64(fileObj);
console.log("convertedFile",convertedFile);
//this is the required function
async function imageToBase64(image) {
const reader = new FileReader();
reader.readAsDataURL(image);
const data= await new Promise((resolve, reject) => {
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
return data;
}
export default imageToBase64;
I need to convert my image to a Base64 string so that I can send my image to a server.
Is there any JavaScript file for this? Else, how can I convert it?
There are multiple approaches you can choose from:
1. Approach: FileReader
Load the image as blob via XMLHttpRequest and use the FileReader API (readAsDataURL()) to convert it to a dataURL:
function toDataURL(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0', function(dataUrl) {
console.log('RESULT:', dataUrl)
})
This code example could also be implemented using the WHATWG fetch API:
const toDataURL = url => fetch(url)
.then(response => response.blob())
.then(blob => new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onloadend = () => resolve(reader.result)
reader.onerror = reject
reader.readAsDataURL(blob)
}))
toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0')
.then(dataUrl => {
console.log('RESULT:', dataUrl)
})
These approaches:
have better compression
work for other file types as well
Browser Support:
http://caniuse.com/#feat=filereader
http://caniuse.com/#feat=fetch
2. Approach: Canvas (for legacy browsers)
Load the image into an Image-Object, paint it to a nontainted canvas and convert the canvas back to a dataURL.
function toDataURL(src, callback, outputFormat) {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function() {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.naturalHeight;
canvas.width = this.naturalWidth;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
};
img.src = src;
if (img.complete || img.complete === undefined) {
img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
img.src = src;
}
}
toDataURL(
'https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0',
function(dataUrl) {
console.log('RESULT:', dataUrl)
}
)
In detail
Supported input formats:
image/png, image/jpeg, image/jpg, image/gif, image/bmp, image/tiff, image/x-icon, image/svg+xml, image/webp, image/xxx
Supported output formats:
image/png, image/jpeg, image/webp(chrome)
Browser Support:
http://caniuse.com/#feat=canvas
Internet Explorer 10 (Internet Explorer 10 just works with same origin images)
3. Approach: Images from the local file system
If you want to convert images from the users file system you need to take a different approach.
Use the FileReader API:
function encodeImageFileAsURL(element) {
var file = element.files[0];
var reader = new FileReader();
reader.onloadend = function() {
console.log('RESULT', reader.result)
}
reader.readAsDataURL(file);
}
<input type="file" onchange="encodeImageFileAsURL(this)" />
You can use the HTML5 <canvas> for it:
Create a canvas, load your image into it and then use toDataURL() to get the Base64 representation (actually, it's a data: URL, but it contains the Base64-encoded image).
This snippet can convert your string, image and even video file to Base64 string data.
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />
<div id="imgTest"></div>
<script type='text/javascript'>
function encodeImageFileAsURL() {
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("imgTest").innerHTML = newImage.outerHTML;
alert("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
console.log("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
}
fileReader.readAsDataURL(fileToLoad);
}
}
</script>
Basically, if your image is
<img id='Img1' src='someurl'>
then you can convert it like
var c = document.createElement('canvas');
var img = document.getElementById('Img1');
c.height = img.naturalHeight;
c.width = img.naturalWidth;
var ctx = c.getContext('2d');
ctx.drawImage(img, 0, 0, c.width, c.height);
var base64String = c.toDataURL();
Here is what I did:
// Author James Harrington 2014
function base64(file, callback){
var coolFile = {};
function readerOnload(e){
var base64 = btoa(e.target.result);
coolFile.base64 = base64;
callback(coolFile)
};
var reader = new FileReader();
reader.onload = readerOnload;
var file = file[0].files[0];
coolFile.filetype = file.type;
coolFile.size = file.size;
coolFile.filename = file.name;
reader.readAsBinaryString(file);
}
And here is how you use it
base64( $('input[type="file"]'), function(data){
console.log(data.base64)
})
I found that the safest and reliable way to do it is to use FileReader().
Demo: Image to Base64
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<input id="myinput" type="file" onchange="encode();" />
<div id="dummy">
</div>
<div>
<textarea style="width:100%;height:500px;" id="txt">
</textarea>
</div>
<script>
function encode() {
var selectedfile = document.getElementById("myinput").files;
if (selectedfile.length > 0) {
var imageFile = selectedfile[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result;
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("dummy").innerHTML = newImage.outerHTML;
document.getElementById("txt").value = document.getElementById("dummy").innerHTML;
}
fileReader.readAsDataURL(imageFile);
}
}
</script>
</body>
</html>
UPDATE - THE SAME CODE WITH COMMENTS FOR #AnniekJ REQUEST:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<input id="myinput" type="file" onchange="encode();" />
<div id="dummy">
</div>
<div>
<textarea style="width:100%;height:500px;" id="txt">
</textarea>
</div>
<script>
function encode() {
// Get the file objects that was selected by the user from myinput - a file picker control
var selectedfile = document.getElementById("myinput").files;
// Check that the user actually selected file/s from the "file picker" control
// Note - selectedfile is an array, hence we check it`s length, when length of the array
// is bigger than 0 than it means the array containes file objects
if (selectedfile.length > 0) {
// Set the first file object inside the array to this variable
// Note: if multiple files are selected we can itterate on all of the selectedfile array using a for loop - BUT in order to not make this example complicated we only take the first file object that was selected
var imageFile = selectedfile[0];
// Set a filereader object to asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.
var fileReader = new FileReader();
// We declare an event of the fileReader class (onload event) and we register an anonimous function that will be executed when the event is raised. it is "trick" we preapare in order for the onload event to be raised after the last line of this code will be executed (fileReader.readAsDataURL(imageFile);) - please read about events in javascript if you are not familiar with "Events"
fileReader.onload = function(fileLoadedEvent) {
// AT THIS STAGE THE EVENT WAS RAISED
// Here we are getting the file contents - basiccaly the base64 mapping
var srcData = fileLoadedEvent.target.result;
// We create an image html element dinamically in order to display the image
var newImage = document.createElement('img');
// We set the source of the image we created
newImage.src = srcData;
// ANOTHER TRICK TO EXTRACT THE BASE64 STRING
// We set the outer html of the new image to the div element
document.getElementById("dummy").innerHTML = newImage.outerHTML;
// Then we take the inner html of the div and we have the base64 string
document.getElementById("txt").value = document.getElementById("dummy").innerHTML;
}
// This line will raise the fileReader.onload event - note we are passing the file object here as an argument to the function of the event
fileReader.readAsDataURL(imageFile);
}
}
</script>
</body>
</html>
If you have a file object, this simple function will work:
function getBase64 (file, callback) {
const reader = new FileReader();
reader.addEventListener('load', () => callback(reader.result));
reader.readAsDataURL(file);
}
Usage example:
getBase64(fileObjectFromInput, function(base64Data){
console.log("Base64 of file is", base64Data); // Here you can have your code which uses Base64 for its operation, // file to Base64 by oneshubh
});
I ended up using a function that returns a Promise.
const getImg64 = async() => {
const convertImgToBase64URL = (url) => {
console.log(url)
return new Promise((resolve, reject) => {
const img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = () => {
let canvas = document.createElement('CANVAS')
const ctx = canvas.getContext('2d')
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0);
const dataURL = canvas.toDataURL();
canvas = null;
resolve(dataURL)
}
img.src = url;
})
}
//for the demonstration purposes I used proxy server to avoid cross origin error
const proxyUrl = 'https://cors-anywhere.herokuapp.com/'
const image = await convertImgToBase64URL(proxyUrl+'https://image.shutterstock.com/image-vector/vector-line-icon-hello-wave-260nw-1521867944.jpg')
console.log(image)
}
getImg64()
You can use this approach in any async function. Then you can just await for the converted image and continue with instructions.
uploadProfile(e) {
let file = e.target.files[0];
let reader = new FileReader();
reader.onloadend = function() {
console.log('RESULT', reader.result)
}
reader.readAsDataURL(file);
}
Here is the way you can do with Javascript Promise.
const getBase64 = (file) => new Promise(function (resolve, reject) {
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result)
reader.onerror = (error) => reject('Error: ', error);
})
Now, use it in event handler.
const _changeImg = (e) => {
const file = e.target.files[0];
let encoded;
getBase64(file)
.then((result) => {
encoded = result;
})
.catch(e => console.log(e))
}
You could use FileAPI, but it's pretty much unsupported.
As far as I know, an image can be converted into a Base64 string either by FileReader() or storing it in the canvas element and then use toDataURL() to get the image. I had the similar kind of problem you can refer this.
Convert an image to canvas that is already loaded
Try this code:
For a file upload change event, call this function:
$("#fileproof").on('change', function () {
readImage($(this)).done(function (base64Data) { $('#<%=hfimgbs64.ClientID%>').val(base64Data); });
});
function readImage(inputElement) {
var deferred = $.Deferred();
var files = inputElement.get(0).files;
if (files && files[0]) {
var fr = new FileReader();
fr.onload = function (e) {
deferred.resolve(e.target.result);
};
fr.readAsDataURL(files[0]);
} else {
deferred.resolve(undefined);
}
return deferred.promise();
}
Store Base64 data in hidden filed to use.
document.querySelector('input').onchange = e => {
const fr = new FileReader()
fr.onloadend = () => document.write(fr.result)
fr.readAsDataURL(e.target.files[0])
}
<input type="file">
Needed to leverage reader to convert blob to base64, prefer to use async-await syntax so I chose to extract reader logic into helper like this:
//* Convert resBlob to base64
export const blobToData = (blob: Blob) => {
return new Promise((resolve) => {
const reader = new FileReader()
reader.onloadend = () => resolve(reader.result)
reader.readAsDataURL(blob)
})
}
and calling it using await in main code:
//* Convert resBlob to dataUrl and resolve
const resData = await blobToData(resBlob)
In the case you are facing cors origin error, there is a simple proxy called cors-fix that loads the image on server and return it as buffer array.
Therefore, we can use fetch to get the image data and filereader to convert it to dataUrl, as described by #HaNdTriX.
function toDataUrl(url) {
fetch(`https://cors-fix.web.app/v1?url=${url}`)
.then(data => data.blob().then(blob => {
const reader = new FileReader();
reader.onloadend = () => {
console.log(reader.result);
};
reader.onerror = () => {
console.log('reader error');
};
reader.readAsDataURL(blob);
}));
}
Well, if you are using Dojo Toolkit, it gives us a direct way to encode or decode into Base64.
Try this:
To encode an array of bytes using dojox.encoding.base64:
var str = dojox.encoding.base64.encode(myByteArray);
To decode a Base64-encoded string:
var bytes = dojox.encoding.base64.decode(str);
You can also simply extract base-64 only part of the URL by ding this:
var Base64URL = canvas.toDataURL('image/webp')
var Base64 = Base64URL.split(",")[1] //Returns the base64 part
Assuming that you are doing this in a browser:
With await:
import axios from 'axios'
const response = await axios.get(url, { responseType: 'blob' });
return window.URL.createObjectURL(response.data);
With promise
import axios from 'axios'
const response = await axios.get(url, { responseType: 'blob' })
.then((response) => {
const dataUrl = window.URL.createObjectURL(response.data);
// do something with your url
});
This is very simple.
1> Just call the function and pass your image.
2> Save the return value and use wherever required.
//call like this
const convertedFile = await imageToBase64(fileObj);
console.log("convertedFile",convertedFile);
//this is the required function
async function imageToBase64(image) {
const reader = new FileReader();
reader.readAsDataURL(image);
const data= await new Promise((resolve, reject) => {
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
return data;
}
export default imageToBase64;
I need to convert my image to a Base64 string so that I can send my image to a server.
Is there any JavaScript file for this? Else, how can I convert it?
There are multiple approaches you can choose from:
1. Approach: FileReader
Load the image as blob via XMLHttpRequest and use the FileReader API (readAsDataURL()) to convert it to a dataURL:
function toDataURL(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0', function(dataUrl) {
console.log('RESULT:', dataUrl)
})
This code example could also be implemented using the WHATWG fetch API:
const toDataURL = url => fetch(url)
.then(response => response.blob())
.then(blob => new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onloadend = () => resolve(reader.result)
reader.onerror = reject
reader.readAsDataURL(blob)
}))
toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0')
.then(dataUrl => {
console.log('RESULT:', dataUrl)
})
These approaches:
have better compression
work for other file types as well
Browser Support:
http://caniuse.com/#feat=filereader
http://caniuse.com/#feat=fetch
2. Approach: Canvas (for legacy browsers)
Load the image into an Image-Object, paint it to a nontainted canvas and convert the canvas back to a dataURL.
function toDataURL(src, callback, outputFormat) {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function() {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.naturalHeight;
canvas.width = this.naturalWidth;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
};
img.src = src;
if (img.complete || img.complete === undefined) {
img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
img.src = src;
}
}
toDataURL(
'https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0',
function(dataUrl) {
console.log('RESULT:', dataUrl)
}
)
In detail
Supported input formats:
image/png, image/jpeg, image/jpg, image/gif, image/bmp, image/tiff, image/x-icon, image/svg+xml, image/webp, image/xxx
Supported output formats:
image/png, image/jpeg, image/webp(chrome)
Browser Support:
http://caniuse.com/#feat=canvas
Internet Explorer 10 (Internet Explorer 10 just works with same origin images)
3. Approach: Images from the local file system
If you want to convert images from the users file system you need to take a different approach.
Use the FileReader API:
function encodeImageFileAsURL(element) {
var file = element.files[0];
var reader = new FileReader();
reader.onloadend = function() {
console.log('RESULT', reader.result)
}
reader.readAsDataURL(file);
}
<input type="file" onchange="encodeImageFileAsURL(this)" />
You can use the HTML5 <canvas> for it:
Create a canvas, load your image into it and then use toDataURL() to get the Base64 representation (actually, it's a data: URL, but it contains the Base64-encoded image).
This snippet can convert your string, image and even video file to Base64 string data.
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />
<div id="imgTest"></div>
<script type='text/javascript'>
function encodeImageFileAsURL() {
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("imgTest").innerHTML = newImage.outerHTML;
alert("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
console.log("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
}
fileReader.readAsDataURL(fileToLoad);
}
}
</script>
Basically, if your image is
<img id='Img1' src='someurl'>
then you can convert it like
var c = document.createElement('canvas');
var img = document.getElementById('Img1');
c.height = img.naturalHeight;
c.width = img.naturalWidth;
var ctx = c.getContext('2d');
ctx.drawImage(img, 0, 0, c.width, c.height);
var base64String = c.toDataURL();
Here is what I did:
// Author James Harrington 2014
function base64(file, callback){
var coolFile = {};
function readerOnload(e){
var base64 = btoa(e.target.result);
coolFile.base64 = base64;
callback(coolFile)
};
var reader = new FileReader();
reader.onload = readerOnload;
var file = file[0].files[0];
coolFile.filetype = file.type;
coolFile.size = file.size;
coolFile.filename = file.name;
reader.readAsBinaryString(file);
}
And here is how you use it
base64( $('input[type="file"]'), function(data){
console.log(data.base64)
})
I found that the safest and reliable way to do it is to use FileReader().
Demo: Image to Base64
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<input id="myinput" type="file" onchange="encode();" />
<div id="dummy">
</div>
<div>
<textarea style="width:100%;height:500px;" id="txt">
</textarea>
</div>
<script>
function encode() {
var selectedfile = document.getElementById("myinput").files;
if (selectedfile.length > 0) {
var imageFile = selectedfile[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result;
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("dummy").innerHTML = newImage.outerHTML;
document.getElementById("txt").value = document.getElementById("dummy").innerHTML;
}
fileReader.readAsDataURL(imageFile);
}
}
</script>
</body>
</html>
UPDATE - THE SAME CODE WITH COMMENTS FOR #AnniekJ REQUEST:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<input id="myinput" type="file" onchange="encode();" />
<div id="dummy">
</div>
<div>
<textarea style="width:100%;height:500px;" id="txt">
</textarea>
</div>
<script>
function encode() {
// Get the file objects that was selected by the user from myinput - a file picker control
var selectedfile = document.getElementById("myinput").files;
// Check that the user actually selected file/s from the "file picker" control
// Note - selectedfile is an array, hence we check it`s length, when length of the array
// is bigger than 0 than it means the array containes file objects
if (selectedfile.length > 0) {
// Set the first file object inside the array to this variable
// Note: if multiple files are selected we can itterate on all of the selectedfile array using a for loop - BUT in order to not make this example complicated we only take the first file object that was selected
var imageFile = selectedfile[0];
// Set a filereader object to asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.
var fileReader = new FileReader();
// We declare an event of the fileReader class (onload event) and we register an anonimous function that will be executed when the event is raised. it is "trick" we preapare in order for the onload event to be raised after the last line of this code will be executed (fileReader.readAsDataURL(imageFile);) - please read about events in javascript if you are not familiar with "Events"
fileReader.onload = function(fileLoadedEvent) {
// AT THIS STAGE THE EVENT WAS RAISED
// Here we are getting the file contents - basiccaly the base64 mapping
var srcData = fileLoadedEvent.target.result;
// We create an image html element dinamically in order to display the image
var newImage = document.createElement('img');
// We set the source of the image we created
newImage.src = srcData;
// ANOTHER TRICK TO EXTRACT THE BASE64 STRING
// We set the outer html of the new image to the div element
document.getElementById("dummy").innerHTML = newImage.outerHTML;
// Then we take the inner html of the div and we have the base64 string
document.getElementById("txt").value = document.getElementById("dummy").innerHTML;
}
// This line will raise the fileReader.onload event - note we are passing the file object here as an argument to the function of the event
fileReader.readAsDataURL(imageFile);
}
}
</script>
</body>
</html>
If you have a file object, this simple function will work:
function getBase64 (file, callback) {
const reader = new FileReader();
reader.addEventListener('load', () => callback(reader.result));
reader.readAsDataURL(file);
}
Usage example:
getBase64(fileObjectFromInput, function(base64Data){
console.log("Base64 of file is", base64Data); // Here you can have your code which uses Base64 for its operation, // file to Base64 by oneshubh
});
I ended up using a function that returns a Promise.
const getImg64 = async() => {
const convertImgToBase64URL = (url) => {
console.log(url)
return new Promise((resolve, reject) => {
const img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = () => {
let canvas = document.createElement('CANVAS')
const ctx = canvas.getContext('2d')
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0);
const dataURL = canvas.toDataURL();
canvas = null;
resolve(dataURL)
}
img.src = url;
})
}
//for the demonstration purposes I used proxy server to avoid cross origin error
const proxyUrl = 'https://cors-anywhere.herokuapp.com/'
const image = await convertImgToBase64URL(proxyUrl+'https://image.shutterstock.com/image-vector/vector-line-icon-hello-wave-260nw-1521867944.jpg')
console.log(image)
}
getImg64()
You can use this approach in any async function. Then you can just await for the converted image and continue with instructions.
uploadProfile(e) {
let file = e.target.files[0];
let reader = new FileReader();
reader.onloadend = function() {
console.log('RESULT', reader.result)
}
reader.readAsDataURL(file);
}
Here is the way you can do with Javascript Promise.
const getBase64 = (file) => new Promise(function (resolve, reject) {
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result)
reader.onerror = (error) => reject('Error: ', error);
})
Now, use it in event handler.
const _changeImg = (e) => {
const file = e.target.files[0];
let encoded;
getBase64(file)
.then((result) => {
encoded = result;
})
.catch(e => console.log(e))
}
You could use FileAPI, but it's pretty much unsupported.
As far as I know, an image can be converted into a Base64 string either by FileReader() or storing it in the canvas element and then use toDataURL() to get the image. I had the similar kind of problem you can refer this.
Convert an image to canvas that is already loaded
Try this code:
For a file upload change event, call this function:
$("#fileproof").on('change', function () {
readImage($(this)).done(function (base64Data) { $('#<%=hfimgbs64.ClientID%>').val(base64Data); });
});
function readImage(inputElement) {
var deferred = $.Deferred();
var files = inputElement.get(0).files;
if (files && files[0]) {
var fr = new FileReader();
fr.onload = function (e) {
deferred.resolve(e.target.result);
};
fr.readAsDataURL(files[0]);
} else {
deferred.resolve(undefined);
}
return deferred.promise();
}
Store Base64 data in hidden filed to use.
document.querySelector('input').onchange = e => {
const fr = new FileReader()
fr.onloadend = () => document.write(fr.result)
fr.readAsDataURL(e.target.files[0])
}
<input type="file">
Needed to leverage reader to convert blob to base64, prefer to use async-await syntax so I chose to extract reader logic into helper like this:
//* Convert resBlob to base64
export const blobToData = (blob: Blob) => {
return new Promise((resolve) => {
const reader = new FileReader()
reader.onloadend = () => resolve(reader.result)
reader.readAsDataURL(blob)
})
}
and calling it using await in main code:
//* Convert resBlob to dataUrl and resolve
const resData = await blobToData(resBlob)
In the case you are facing cors origin error, there is a simple proxy called cors-fix that loads the image on server and return it as buffer array.
Therefore, we can use fetch to get the image data and filereader to convert it to dataUrl, as described by #HaNdTriX.
function toDataUrl(url) {
fetch(`https://cors-fix.web.app/v1?url=${url}`)
.then(data => data.blob().then(blob => {
const reader = new FileReader();
reader.onloadend = () => {
console.log(reader.result);
};
reader.onerror = () => {
console.log('reader error');
};
reader.readAsDataURL(blob);
}));
}
Well, if you are using Dojo Toolkit, it gives us a direct way to encode or decode into Base64.
Try this:
To encode an array of bytes using dojox.encoding.base64:
var str = dojox.encoding.base64.encode(myByteArray);
To decode a Base64-encoded string:
var bytes = dojox.encoding.base64.decode(str);
You can also simply extract base-64 only part of the URL by ding this:
var Base64URL = canvas.toDataURL('image/webp')
var Base64 = Base64URL.split(",")[1] //Returns the base64 part
Assuming that you are doing this in a browser:
With await:
import axios from 'axios'
const response = await axios.get(url, { responseType: 'blob' });
return window.URL.createObjectURL(response.data);
With promise
import axios from 'axios'
const response = await axios.get(url, { responseType: 'blob' })
.then((response) => {
const dataUrl = window.URL.createObjectURL(response.data);
// do something with your url
});
This is very simple.
1> Just call the function and pass your image.
2> Save the return value and use wherever required.
//call like this
const convertedFile = await imageToBase64(fileObj);
console.log("convertedFile",convertedFile);
//this is the required function
async function imageToBase64(image) {
const reader = new FileReader();
reader.readAsDataURL(image);
const data= await new Promise((resolve, reject) => {
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
return data;
}
export default imageToBase64;