Display Image Before Uploading

To enhance the user experience of file uploads in a web application, we can use JavaScript and the URL class to preview images before they are uploaded. First, create an HTML input element of type “file” and an HTML image element for displaying the preview. Add an event listener to detect file selection. Access the selected file using the input element’s “files” property. Use the URL class and createObjectURL() method to generate a temporary URL representing the file. Set the image element’s src attribute to the generated URL to display the image preview. To handle non-image files or cancellations, verify the file type using the “type” property. Remember that the temporary URL is session-specific and will be automatically revoked by the browser at the session’s end.

<div>

    <input type="file" name="partner_logo" id="partner_logo" class="form-control"  onchange="previewImage(event);" /><br/>
    <span id="msg" style="color:red"></span>
    </div>

     <div class="preview">
        <img id="preview-selected-image" />
    </div>

<script>

const previewImage = (event) => {
    const imageFiles = event.target.files;
    const imageFilesLength = imageFiles.length;
    if (imageFilesLength > 0) {
        const imageSrc = URL.createObjectURL(imageFiles[0]);
        const imagePreviewElement = document.querySelector("#preview-selected-image");
        imagePreviewElement.src = imageSrc;
        imagePreviewElement.style.display = "block";
        imagePreviewElement.style.width = "300px";
        imagePreviewElement.style.height = "100px";
        imagePreviewElement.style.border = "1px solid #ccc";
    }
};

 
 </script>

 

Leave a Reply