Explain Codes LogoExplain Codes Logo

Using HTML5 file uploads with AJAX and jQuery

html
file-reader
ajax
file-upload
Alex KataevbyAlex Kataev·Jan 19, 2025
TLDR

Achieve rapid files uploads with AJAX and jQuery by exploiting the capabilities of the FormData object. Attach your file input to the form data and kick off an $.ajax POST request. Remember to configure both contentType and processData to false to ensure smooth file transmission. Consider this compact script:

var formData = new FormData(); formData.append('file', $('#fileInput')[0].files[0]); // Don't forget to adjust the ID to match your input $.ajax({ url: 'upload.php', // Server script that processes the upload type: 'POST', data: formData, contentType: false, processData: false, success: (data) => console.log('Upload readily successful!', data), error: (jqXHR) => console.error('Oops! Upload failed!', jqXHR.statusText) });

This lightweight boilerplate kindles rapid file uploads in your web applications.

Client-side manoeuvre

Life is too short to wait for server validation. Utilize the FileReader API for client-side check and validation of files. It allows reading of files as a BinaryString, DataUrl, or ArrayBuffer. This illustration helps to preview an image before uploading it using readAsDataURL:

var reader = new FileReader(); reader.onload = function (e) { $('#preview').attr('src', e.target.result); // Voilà, image preview at your service }; reader.readAsDataURL($('#fileInput')[0].files[0]);

This practice is vital as it confirms the appropriateness of the file before the actual time-consuming upload takes off.

Art of form submission interception

Stealth meets strategy in file upload workflows. Hook an event listener to your form's submit action to block default behaviour and grab file data. This illustration uses jQuery to silently thumb a ride on your submit action and launch your custom AJAX logic:

$('#uploadForm').on('submit', function(e) { e.preventDefault(); // Stops form from submitting normally... Sneaky, isn't it? var formData = new FormData(this); // Attach additional data if necessary, because we love to spoil our users formData.append('timestamp', Date.now()); // ... AJAX request remains the same as above });

Secure server-side file stewardship

Security is king on the server side. While writing files to the server via PHP, always sanitize inputs and think of consolidating a timestamp or unique identifier to file names to avert overwriting. Plus, operate file-access functions like fwrite() safely and feel the pulse of errors through the process:

$filename = time() . '-' . basename($_FILES["file"]["name"]); if (move_uploaded_file($_FILES["file"]["tmp_name"], $uploadDir . $filename)) { echo "The file ". htmlspecialchars($filename). " has been uploaded like an obedient pet."; } else { echo "Sorry, your file decided to be rebellious: there was an error uploading it."; }

Progress tracking and refinement of user experience

FileType = 'Too Big', UploadSpeed = 'Too Slow'; // Avoid these awkward conversations by tuning progress indicators. Utilize 📮 xhr event listeners to track and display progress bars:

$.ajax({ // ... xhr: function() { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener('progress', function(e) { if (e.lengthComputable) { var percentComplete = e.loaded / e.total * 100; $('#progressBar').val(percentComplete); // Time to pop the champagne, progress bar updated! } }, false); return xhr; } });

This fantastic approach keeps your user informed like a personal assistant, providing real-time status of their upload.

Diving into advanced scenarios

Don't limit yourself to the basics, let's tackle some real-world scenarios:

Sailing through file floods (Multiple file uploads)

The tide of multiple files is a walk in the park. Just iterate over them:

var files = $('#multipleFileInput')[0].files; for (var i = 0, file; file = files[i]; i++) { // Create new formData object for each file, because we believe in personal space var formData = new FormData(); formData.append('file', file); // Make a separate AJAX call for each file // ... (like dispatching homing pigeons individually to the same destination) }

Drag, drop and chill!

Modern web applications often necessitate a drag-and-drop feature. HTML5 to the rescue!

<div id="dropZone">Drop files here or aliens will abduct them</div>

Attach an event listener for the drop events and utilize FormData like you did for submissions:

$('#dropZone').on('drop', function(e) { e.preventDefault(); var files = e.originalEvent.dataTransfer.files; // ... (Go on with your form input files) });

Robust error handling is the new cool

Everything seems perfect until something goes wrong. Solid error handling is thus crucial. Imagine server-side validations that return understandable error messages for the user:

if ($_FILES["file"]["size"] > 4000000) {// Arbitrary file size limit because anything more would break the scale die(json_encode(["error" => "File size limit exceeded, try dieting it a bit."])); }

Fetch and display errors gracefully via AJAX callbacks:

// ... (in your $.ajax call) error: function(jqXHR, textStatus, errorThrown) { var errorObj = JSON.parse(jqXHR.responseText); alert(errorObj.error); // Toasts a user-friendly error message }

Metadata tracking in the database

Stash the metadata of uploaded files in your database for later use. Use PHP to plug metadata into your database post-upload:

// Assume you're connected to the database (e.g., via PDO or mysqli) $stmt = $db->prepare("INSERT INTO uploaded_files (filename, size, upload_time) VALUES (?, ?, ?)"); $stmt->bind_param("sis", $filename, $filesize, $timestamp); $stmt->execute();

Always dodge data attacks or use prepared statements to guard against SQL injection attacks.

Safeguarding uploads

Safety first! Apart from timestamps and unique identifiers for filenames, ensure your server-side script audits the file type and size. Set your server to disallow execution of uploaded files and regularly scan for malware.