Converting JavaScript file objects or blobs to Base64 strings can be useful. For example when we can only send string based data to the server. In this tutorial weโll explore how to use JavaScript to generate a Base64 string and a DataURL from a file object.
In both examples weโll use a file obtained from a file input field.
Encoding a File as a DataURL
We use FileReader to convert the file object to a dataUR this is done by using the readAsDataURL
method.
<input type="file" />
<script>
// get a reference to the file input
const fileInput = document.querySelector("input");
// listen for the change event so we can capture the file
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 = () => {
// log to console
// logs data:<type>;base64,wL2dvYWwgbW9yZ...
console.log(reader.result);
};
reader.readAsDataURL(file);
});
</script>
Encoding the File as a Base64 string
The snippet below creates a base64 string, itโs identical to the previous example but it uses a regular expression to remove the Data URL part.
<input type="file" />
<script>
// get a reference to the file input
const fileInput = document.querySelector("input");
// listen for the change event so we can capture the file
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);
});
</script>
Generating a URL that points to a File object
Sometimes we just want to use an File
object as an image source. But how to add the file object to the <img>
src
attribute?
The URL.createObjectURL()
method can help here.
The following code snippet will update the image source to the file that is loaded in the file input.
<input type="file" accept="image/*" />
<img src="" alt="" />
<script>
// get a reference to the file input
const imageElement = document.querySelector("img");
// get a reference to the file input
const fileInput = document.querySelector("input");
// listen for the change event so we can capture the file
fileInput.addEventListener("change", (e) => {
// get a reference to the file
const file = e.target.files[0];
// set file as image source
imageElement.src = URL.createObjectURL(file);
});
</script>
We need to make sure to revoke the URL if we no longer need the file. If we donโt this causes memory leaks.
URL.revokeObjectURL(fileUrl);
Thatโs it! - Source
Now It's Time to convert a URL file to Base64
Let's we have an Image Here :- https://Gurimg.sh20raj.repl.co/logo.jpg
Here is the Function...
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();
}
Here is the function you have to run and get the image base64 on your console.
toDataUrl("https://Gurimg.sh20raj.repl.co/logo.jpg", function(myBase64) {
console.log(myBase64); // myBase64 is the base64 string
});
Checkout Instagram :-
Top comments (1)
Nice ๐
And we have WebScrapperJS to pass cors...