Course contentsShow
← JavaScript
Lesson 2369 of 2,72348. Working with Binary DataFree lesson

Creating Object URLs

Generate temporary URLs for Blobs using URL.createObjectURL() for displaying or downloading binary data.

Creating Object URLs

You'll learn how to generate temporary URLs for Blobs and Files so you can display images, videos, or trigger downloads without uploading files to a server.

What is an Object URL?

When you have binary data in a Blob or File object, you can't directly set it as the src of an image or link—it's just bytes in memory. An Object URL is a special temporary URL (starting with blob:) that points to that in-memory data. Think of it like getting a temporary street address for data that only lives in your browser's RAM.

Using URL.createObjectURL()

The URL.createObjectURL() method takes a Blob or File and returns a string URL you can use anywhere a normal URL works:

const blob = new Blob(['<h1>Hello World</h1>'], { type: 'text/html' });
const url = URL.createObjectURL(blob);

console.log(url); // "blob:http://example.com/abc123-def456..."

Now you can use this URL to display images, download files, or open documents:

// Display an image from file input
const fileInput = document.querySelector('input[type="file"]');
fileInput.addEventListener('change', (e) => {
  const file = e.target.files[0];
  const imageUrl = URL.createObjectURL(file);
  
  const img = document.createElement('img');
  img.src = imageUrl;
  document.body.appendChild(img);
});

Cleaning Up with URL.revokeObjectURL()

Object URLs keep the Blob in memory. When you're done, revoke the URL to free memory:

URL.revokeObjectURL(imageUrl);

This is especially important in long-running applications where users might upload many files.

Key Takeaway: URL.createObjectURL() creates temporary blob: URLs for in-memory binary data, enabling you to display or download Blobs and Files without server uploads—just remember to revoke them when finished.