DEV Community

payam1382
payam1382

Posted on

Optimized File Upload Speed with HTML and JavaScript

<!DOCTYPE html>




Optimized File Upload Speed
<br> body {<br> font-family: Arial, sans-serif;<br> margin: 20px;<br> }<br> input[type=&quot;file&quot;] {<br> margin: 20px 0;<br> }<br> #status {<br> margin-top: 20px;<br> }<br>


Optimized File Upload Speed

<form id="uploadForm">
    <input type="file" id="fileInput" multiple>
    <button type="button" onclick="uploadFiles()">Upload Files</button>
</form>

<div id="status"></div>

<script>
    function uploadFiles() {
        const input = document.getElementById('fileInput');
        const statusDiv = document.getElementById('status');
        const files = input.files;

        if (files.length === 0) {
            statusDiv.textContent = 'Please select files to upload.';
            return;
        }

        statusDiv.textContent = 'Uploading...';

        // Create a FormData object
        const formData = new FormData();
        for (let i = 0; i < files.length; i++) {
            formData.append('files[]', files[i]);
        }

        // Create an XMLHttpRequest object
        const xhr = new XMLHttpRequest();

        // Set up a handler for the `load` event
        xhr.onload = function () {
            if (xhr.status === 200) {
                statusDiv.textContent = 'Files uploaded successfully!';
            } else {
                statusDiv.textContent = 'Upload failed. Please try again.';
            }
        };

        // Set up a handler for the `error` event
        xhr.onerror = function () {
            statusDiv.textContent = 'An error occurred. Please try again.';
        };

        // Open the request and send the FormData object
        xhr.open('POST', 'your-server-endpoint-url', true);
        xhr.send(formData);
    }
</script>



MLKED.COM

Top comments (0)