Validate and Show Preview of Single or Multiple Image before Upload in Server with JavaScript



Hello, friend's in this tutorial I'm going to show you how we can display preview of image in our webpage after select from file input field, here we are not going to upload image file in web server, we will just show preview of selected image file in client browser using javascript.

Source code to Validate and show Preview of Single or Multiple Image before upload in server with Javascript


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Preview image before upload, with Javascript</title>
    <!--Regex to validate image => ("[^\\s]+(.*?)\\.(jpg|jpeg|png|gif|JPG|JPEG|PNG|GIF)$") -->
    <!--Tutorial Link : https://youtu.be/QxRIyuNNzoM-->
</head>
<body>
    <input type="file" multiple>
    <div></div>
    <script>
        let input = document.querySelector("input");
        let div = document.querySelector("div")
        input.addEventListener("change", e => {
            console.log(e.target.files);
            Array.from(e.target.files).forEach(item => {
                if (item.name.match("[^\\s]+(.*?)\\.(jpg|jpeg|png|gif|JPG|JPEG|PNG|GIF)$")) {
                    div.innerHTML += `
                <img src="${item.name}"height="200"width="300">
                `;
                } else {
                    alert("please select a valid image file")
                }
            })
            // for single file preview
            // if (e.target.files[0].name.match("[^\\s]+(.*?)\\.(jpg|jpeg|png|gif|JPG|JPEG|PNG|GIF)$")) {
            //     div.innerHTML = `
            //     <img src="${e.target.files[0].name}"height="200"width="300">
            //     `;
            // } else {
            //     alert("please select a valid image file")
            // }
        })
    </script>

</body>
</html>



More Posts For You!


5 More HTML Tricks For You

5 HTML Tricks That You Can Use To Enhance Your Web Pages

Effortlessly Convert Excel to JSON with JavaScript: Streamline Your Data Management with Sheet Js

Integrating OCR Capabilities into Web Applications with JavaScript and AppScript

Efficient Text Extraction from PDFs: Implementing OCR with JavaScript and AppScript

Build a CRUD Application Using Google Sheets as Database with HTML, CSS, and JavaScript

Integrating OpenAI with Google Sheets using AppScript for Automated Responses

Upload Images to Google Drive and Google Sheets from HTML File Input: A Complete JavaScript and AppScript Guide

Convert HTML and CSS to PDF with JavaScript Using HTML2PDF.js

Create a Functional Contact Form Using HTML, CSS, JavaScript, and Google AppScript

Build a CRUD App Using HTML, CSS, JavaScript, and IndexedDB API

Reading Data From Google Sheets to HTML Using JavaScript and Apps Script

PrevNext