Open In App

HTML DOM createObjectURL() method

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:

Parameters

Description

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.






<!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:


Article Tags :