HTML DOM createObjectURL() method
Last Updated :
29 Dec, 2023
The createObjectURL() method creates a DOMString containing a URL representing the object given in the parameter of the method. The new object URL represents the specified File object or Blob object.
Note: The URL lifetime is tied to the document in which it was created and To release an object URL, call revokeObjectURL()
.
Syntax:
const url = URL.createObjectURL(object);
Parameters:
object
|
A File, image, or any other MediaSource object for which the object URL is to be created.
|
Return value
|
A DOMString containing an object URL of that object.
|
Usage :
When using createObjectURL()
in your code, remember to call URL.revokeObjectURL()
for each object URL created when it’s no longer needed. This helps manage memory efficiently. While browsers release object URLs automatically when the document is unloaded, manually revoking them at safe times can improve performance and reduce memory usage.
Example: In this example, we will create an object URL for the image object using this method.
html
<!DOCTYPE html>
< html >
< head >
< meta charset = "utf-8" >
< title >URL.createObjectURL example</ title >
</ head >
< body >
< h1 >GeeksforGeeks</ h1 >
< input type = "file" >
< img >
< p class = "p" >The URL of this image is : </ p >
</ body >
< script >
let Element = document.querySelector('input');
let img = document.querySelector('img');
Element.addEventListener('change', function () {
let url = URL.createObjectURL(Element.files[0]);
img.src = url;
console.log(url);
let d = document.querySelector(".p");
d.textContent += url;
});
</ script >
</ html >
|
Output:
Supported Browsers:
- Google Chrome 19 and above
- Edge 12 and above
- Firefox 19 and above
- Safari 6 and above
- Opera 15 and above
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...