URL.createObjectURL: Preview Files Locally in JavaScript - 🙏 Namaste React

0
URL.createObjectURL: Preview Files Locally in JavaScript
React useRef Hook Example

Mastering URL.createObjectURL: Preview Files Locally in JavaScript


Introduction

The URL.createObjectURL() method in JavaScript is a powerful tool for generating temporary, unique URLs that represent local files. This is particularly useful for previewing images, videos, or other files on the client side without uploading them to a server.


How Does It Work?

When a user selects a file from their system, URL.createObjectURL() creates a unique Blob URL that points to the file. This URL can be used to preview the file directly in the browser. Here's a basic workflow:

  • User selects a file via an <input> element.
  • The file object is passed to URL.createObjectURL().
  • A unique URL is generated (e.g., blob:http://localhost:3000/12345).
  • This URL is used to display the file content, such as an image preview.

Use Case

A common use case for URL.createObjectURL() is creating an image preview when a user uploads a file. This approach avoids unnecessary server interactions during development and provides immediate feedback to the user.


Example Code

Here’s a React example demonstrating how to use URL.createObjectURL():

import React, { useState } from "react";

const FilePreview = () => {
  const [imageFile, setImageFile] = useState(null);
  const [imageFileUrl, setImageFileUrl] = useState(null);

  const handleImageChange = (e) => {
    const file = e.target.files[0];
    if (file) {
      setImageFile(file); // Save file data
      setImageFileUrl(URL.createObjectURL(file)); // Generate Blob URL
    }
  };

  return (
    <div>
  <input type="file" accept="image/*" onChange={handleImageChange} />
  {imageFileUrl && (
    <div className="image-preview">
      <img src={imageFileUrl} alt="Preview" />
    </div>
  )}
</div>

  );
};

export default FilePreview;

                

Result

When you select an image file, a preview is displayed instantly using the generated Blob URL:

Preview Placeholder

If any issue or feeback , you can reach me out here :

Post a Comment

0Comments
Post a Comment (0)
To Top