An ObjectUrl is the representation of blob object as a data URL strings that can be used with any fetch HTML element that accepts an URL as an attribute.
Example: This HTML was generated with the code in the next example.
<a href="blob:https://datacadamia.com/35a824bb-3a18-42d0-81c9-24df9aa548b2">Hello-world.txt</a>
The id blob:https://datacadamia.com/4067f3b2-dba2-4bdc-8199-e86fd670aa67 is:
The javascript browser api function URL.createObjectURL creates an ObjectUrl that represents a data uri that can then be passed as URL.
Example to download a text file:
let textBlob = new Blob( ["Hello World !"], { type: 'text/plain' });
let objectUrl = URL.createObjectURL(textBlob);
let a = document.createElement("a");
document.body.append(a);
a.href=objectUrl;
let fileName = "hello-world.txt";
a.setAttribute("download",fileName);
a.innerText = `Download ${fileName}`;
// To prevent memory leaks, always revoke the URL after the download.
a.addEventListener('click', (e) => {
setTimeout(() => URL.revokeObjectURL(e.target.href), 30 * 1000);
});
You can create a ObjectURL with the URL function URL.createObjectURL()
const objectURL = URL.createObjectURL(object)
where: the object parameter may be a File, Blob, or MediaSource object
Usage as src or href
img.src = URL.createObjectURL(object);
a.href = URL.createObjectURL(object);
Because createObjectURL creates at each invocation a new object, you need to delete it with the URL.revokeObjectURL() method after usage.
img.onload = function() {
URL.revokeObjectURL(this.src);
}
a.addEventListener('click', (e) => {
setTimeout(() => URL.revokeObjectURL(e.target.href), 30 * 1000);
});
You can get a blob object by fetching the URL
let blob = await fetch(url).then(r => r.blob());