How to Limit File Upload Size and Provide Progress Feedback in JavaScript? [closed]

  1. File Size Limitation: Users should not be able to upload files larger than 2 MB. If they attempt to do so, I want to display a warning message.

  2. Upload Progress Feedback: While the file is uploading, I want to show a progress bar that indicates how much of the file has been uploaded.

    Below is the code I have so far

    html

    <!-- The HTML form for file upload -->
    <form id="uploadForm">
        <input type="file" id="fileInput" accept="image/*" required />
        <div id="progressContainer" style="display: none;">
            <progress id="uploadProgress" value="0" max="100"></progress>
            <span id="progressText"></span>
        </div>
        <button type="submit">Upload</button>
    </form>
    
    

    js

    <script>
        // Event listener for the form submission
        document.getElementById('uploadForm').addEventListener('submit', function(event) {
            event.preventDefault(); // Prevent default form submission
    
            const fileInput = document.getElementById('fileInput');
            const file = fileInput.files[0]; // Get the selected file
            const maxSize = 2 * 1024 * 1024; // Set the maximum file size to 2 MB
    
            // Check if the selected file exceeds the maximum size
            if (file.size > maxSize) {
                alert('File size exceeds 2 MB. Please select a smaller file.');
                return; // Stop the function if the file is too large
            }
    
            // Prepare the form data for upload
            const formData = new FormData();
            formData.append('file', file);
    
            // Show the progress container for upload feedback
            const progressContainer = document.getElementById('progressContainer');
            const uploadProgress = document.getElementById('uploadProgress');
            const progressText = document.getElementById('progressText');
    
            progressContainer.style.display = 'block'; // Show the progress container
    
            // Create a new XMLHttpRequest for file upload
            const xhr = new XMLHttpRequest();
            xhr.open('POST', '/upload', true); // Specify the upload endpoint
    
            // Update the progress bar during the upload
            xhr.upload.addEventListener('progress', function(e) {
                if (e.lengthComputable) {
                    const percentComplete = (e.loaded / e.total) * 100;
                    uploadProgress.value = percentComplete; // Update the progress value
                    progressText.textContent = Math.round(percentComplete) + '% uploaded'; // Update the text
                }
            });
    
            // Handle the response after upload completion
            xhr.onload = function() {
                if (xhr.status === 200) {
                    console.log('Upload complete:', JSON.parse(xhr.responseText)); // Log success
                } else {
                    console.error('Upload failed:', xhr.statusText); // Log error
                }
            };
    
            // Start the upload
            xhr.send(formData);
        });
    </script>
    
    

    I need to ensure that the upload process does not initiate when a large file is selected.

    I want the progress bar to only appear during the upload. How can I manage its visibility effectively?

    Are there any additional features or best practices I should consider for a better user experience regarding file uploads?