Saturday, November 2, 2024

JavaScript fetch API to display an image from local folder in HTML page

To use the Fetch API to display an image stored in a local folder on an HTML page, you'll typically serve your HTML file from a local server (Which may be LiveServer in VS Code or a simple HTTP server created using Node express module etc.) because browsers restrict direct file access due to security reasons. Here's how to do it:

Set Up Your Project Directory:
Create a folder for your project. Inside this folder, create another folder named images (or any name you prefer) where you will store your images. Place your image files (e.g., logo.png) inside the images folder.

Create Your HTML File:
Create an HTML file (e.g., index.html) in your project folder.

Directory Structure:
/your-project-folder
├── /images
│   └── logo.png
└── index.html
index.html

Write the JavaScript Code in HTML file:
Use the Fetch API to load the image and display it. Here’s an example of what your index.html file might look like:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Display Local Image</title>
</head>
<body>
    <h1>Image from Local Folder</h1>
    <img id="image" alt="Loaded from local folder" />

    <script>
        // Function to fetch and display the image
        async function fetchImage() {
            const imagePath = './images/logo.png'; // Relative path to the image

            try {
                const response = await fetch(imagePath);
                
                // Check if the response is ok (status code 200-299)
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }

                const blob = await response.blob(); // Get the image as a Blob
                const imageObjectURL = URL.createObjectURL(blob); // Create a URL for the Blob

                // Set the src of the img element to the Blob URL
                document.getElementById('image').src = imageObjectURL;
            } catch (error) {
                console.error('Error fetching image:', error);
            }
        }

        // Call the function to fetch and display the image
        fetchImage();
    </script>
</body>
</html>
Explanation of the Code
HTML Structure: Basic HTML structure with an <img> element where the image will be displayed.
JavaScript Function: The fetchImage() function constructs the relative path to the image. It calls the Fetch API to get the image. If the response is successful, it converts the response to a Blob.
A URL representing the Blob is created using URL.createObjectURL().
Finally, the src attribute of the <img> element is set to this Blob URL, displaying the image on the page.

Running the Project
To view the image, start a Local Server. You can use simple servers like Live Server extension in Visual Studio Code (VS Code) to display an image from a local folder. Live Server provides a simple way to launch a local development server with live reload capabilities, making it easy to see changes in real time.

Install Live Server Extension:
  1. Open Visual Studio Code.
  2. Go to the Extensions view by clicking on the Extensions icon in the Activity Bar on the side of the window or by pressing Ctrl+Shift+X.
  3. Search for "Live Server" and install it.
Benefits of Using Live Server
  1. Automatic Reloading: Any changes you make to your HTML, CSS, or JavaScript files will automatically refresh in the browser.
  2. Local Development Environment: It mimics a real server environment, making it easier to test web applications without CORS issues or file access restrictions.
Using Live Server in VS Code is a great way to develop and test your web projects quickly!

No comments:

Post a Comment

Hot Topics