Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Using HTML5 file uploads with AJAX and jQuery
HTML5 provides robust support for file uploads using AJAX and jQuery, allowing you to upload files asynchronously without page refresh. This approach uses the File API to read file contents on the client side and send them to the server via AJAX requests.
Syntax
Following is the basic syntax for HTML5 file input −
<input type="file" id="fileBox" name="file">
JavaScript FileReader API syntax −
var reader = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onload = function(event) { /* handle result */ };
Client-Side Implementation
The client-side code captures the file upload process and uses the FileReader API to read the file contents before sending them to the server via jQuery AJAX.
Example − Complete File Upload with AJAX
<!DOCTYPE html>
<html>
<head>
<title>HTML5 File Upload with AJAX</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>File Upload with AJAX</h2>
<form id="uploadForm">
<input type="file" id="fileBox" name="file" accept=".txt,.csv,.json">
<button type="submit">Upload File</button>
</form>
<div id="result" style="margin-top: 20px; padding: 10px; border: 1px solid #ccc;"></div>
<script>
$('#uploadForm').on('submit', function(e) {
e.preventDefault();
var myFile = document.getElementById('fileBox').files[0];
if (!myFile) {
$('#result').html('<span style="color: red;">Please select a file</span>');
return;
}
var reader = new FileReader();
reader.readAsText(myFile, 'UTF-8');
reader.onload = myFunc;
});
function myFunc(event) {
var res = event.target.result;
var fileName = document.getElementById('fileBox').files[0].name;
$('#result').html('Uploading file: ' + fileName + '...');
$.post('/myscript.php', {
data: res,
name: fileName
}, continueSubmission).fail(function() {
$('#result').html('<span style="color: red;">Upload failed</span>');
});
}
function continueSubmission(response) {
var data = JSON.parse(response);
$('#result').html('<span style="color: green;">File uploaded successfully: ' + data.myServerFile + '</span>');
}
</script>
</body>
</html>
This example creates a complete file upload interface with error handling and success feedback. The form prevents default submission and handles file reading asynchronously.
Server-Side Implementation
On the server side, the script receives the file data and filename, then saves the file with a unique timestamp prefix to prevent overwriting existing files.
PHP Server Script (myscript.php)
<?php
$data = $_POST['data'];
$fileName = $_POST['name'];
$myServerFile = time() . '_' . $fileName;
// Create uploads directory if it doesn't exist
if (!file_exists('/uploads/')) {
mkdir('/uploads/', 0777, true);
}
// Prevent overwriting and save file
$fp = fopen('/uploads/' . $myServerFile, 'w');
fwrite($fp, $data);
fclose($fp);
$retData = array("myServerFile" => $myServerFile);
echo json_encode($retData);
?>
Using FormData for Binary Files
For binary files like images or documents, use FormData instead of FileReader to maintain file integrity.
Example − Binary File Upload
<!DOCTYPE html>
<html>
<head>
<title>Binary File Upload with AJAX</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Upload Images or Documents</h2>
<form id="binaryForm">
<input type="file" id="binaryFile" name="file" accept="image/*,.pdf,.doc,.docx">
<button type="submit">Upload Binary File</button>
</form>
<div id="binaryResult" style="margin-top: 20px; padding: 10px; border: 1px solid #ccc;"></div>
<script>
$('#binaryForm').on('submit', function(e) {
e.preventDefault();
var fileInput = document.getElementById('binaryFile');
var file = fileInput.files[0];
if (!file) {
$('#binaryResult').html('<span style="color: red;">Please select a file</span>');
return;
}
var formData = new FormData();
formData.append('file', file);
$('#binaryResult').html('Uploading: ' + file.name + '...');
$.ajax({
url: '/upload-binary.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(response) {
var data = JSON.parse(response);
$('#binaryResult').html('<span style="color: green;">File uploaded: ' + data.fileName + '</span>');
},
error: function() {
$('#binaryResult').html('<span style="color: red;">Upload failed</span>');
}
});
});
</script>
</body>
</html>
For binary files, FormData preserves the original file format and handles encoding automatically. Set processData: false and contentType: false in the AJAX settings.
File Upload Progress Tracking
You can track upload progress using the XMLHttpRequest progress event for better user experience.
Example − Upload with Progress Bar
<!DOCTYPE html>
<html>
<head>
<title>File Upload with Progress</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Upload with Progress Tracking</h2>
<form id="progressForm">
<input type="file" id="progressFile" name="file">
<button type="submit">Upload with Progress</button>
</form>
<div id="progressContainer" style="display: none; margin-top: 20px;">
<div style="background: #f0f0f0; border-radius: 5px; padding: 3px;">
<div id="progressBar" style="background: #4CAF50; height: 20px; border-radius: 3px; width: 0%;"></div>
</div>
<div id="progressText" style="margin-top: 5px;">0%</div>
</div>
<script>
$('#progressForm').on('submit', function(e) {
e.preventDefault();
var file = document.getElementById('progressFile').files[0];
if (!file) return;
var formData = new FormData();
formData.append('file', file);
$('#progressContainer').show();
$.ajax({
url: '/upload-progress.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round((evt.loaded / evt.total) * 100);
$('#progressBar').css('width', percentComplete + '%');
$('#progressText').text(percentComplete + '%');
}
}, false);
return xhr;
},
success: function(response) {
$('#progressText').text('Upload complete!');
}
});
});
</script>
</body>
</html>
Key Points
-
FileReader API − Use
readAsText()for text files,readAsDataURL()for images, or FormData for binary files. -
Error handling − Always check if a file is selected and handle AJAX errors gracefully.
-
File validation − Use the
acceptattribute on file inputs to restrict file types. -
Security − Validate file types and sizes on the server side to prevent malicious uploads.
-
Progress tracking − Implement upload progress indicators for better user experience with large files.
Browser Compatibility
The File API and FormData are supported in all modern browsers including Chrome, Firefox, Safari, and
