The easiest way to upload files in the web application is to use server-side code. The file upload functionality can be implemented with minimal lines of code in the server-side script. In the previous tutorial, we discussed a simple method to upload files in PHP. Today we’ll build a simple Ajax file upload script with jQuery and PHP. The main purpose of the Ajax file upload functionality is to allow the user to upload files to the server without page refresh.
There are various jQuery plugins are available to upload files or images without page refresh. But if you want to learn the Ajax file upload process and make your own Ajax file upload script, this step-by-step tutorial will help you a lot.
Here we’ll show how you can upload files to the server without page refresh using jQuery, Ajax, and PHP. Using our simple Ajax file upload script, you can easily implement file upload functionality without using any 3rd party plugin.
Define some HTML elements to display the file uploader container. The user can select a file to upload by clicking on this container element.
<form>
<div id="dropBox">
<p>Select file to upload</p>
</div>
<input type="file" name="fileInput" id="fileInput" />
</form>
Define CSS to make the file uploader box look good and hide the default file select input.
#dropBox{
border: 3px dashed #0087F7;
border-radius: 5px;
background: #F3F4F5;
cursor: pointer;
}
#dropBox{
min-height: 120px;
padding: 35px;
box-sizing: border-box;
}
#dropBox p{
text-align: center;
margin: 2em 0;
font-size: 17px;
font-weight: bold;
}
#fileInput{
display: none;
}
First, include the jQuery library that is used to initialize the Ajax request and handle the upload process at the client-side.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
The following JavaScript code handles the file upload process using Ajax.
#dropBox
) is clicked, the file input field (#fileInput
) is trigger using jQuery click()
method.fileUpload()
function initialize the XMLHttpRequest to post the file data to the server-side script (upload.php
).allowedFileTypes
variable to specify the file types that are allowed to upload (For example, we have set images and PDF files as allowed file types.).allowedFileSize
variable to set the maximum size of the file that can be uploaded (For example, we have set 1024KB/1MB as the maximum file size.).<script>
$(function(){
// File input field trigger when the HTML element is clicked
$("#dropBox").click(function(){
$("#fileInput").click();
});
// Prevent browsers from opening the file when its dragged and dropped
$(document).on('drop dragover', function (e) {
e.preventDefault();
});
// Call a function to handle file upload on select file
$('input[type=file]').on('change', fileUpload);
});
function fileUpload(event){
// Allowed file types
var allowedFileTypes = 'image.*|application/pdf'; //text.*|image.*|application.*
// Allowed file size
var allowedFileSize = 1024; //in KB
// Notify user about the file upload status
$("#dropBox").html(event.target.value+" uploading...");
// Get selected file
files = event.target.files;
// Form data check the above bullet for what it is
var data = new FormData();
// File data is presented as an array
for (var i = 0; i < files.length; i++) {
var file = files[i];
if(!file.type.match(allowedFileTypes)) {
// Check file type
$("#dropBox").html('<p class="error">File extension error! Please select the allowed file type only.</p>');
}else if(file.size > (allowedFileSize*1024)){
// Check file size (in bytes)
$("#dropBox").html('<p class="error">File size error! Sorry, the selected file size is larger than the allowed size (>'+allowedFileSize+'KB).</p>');
}else{
// Append the uploadable file to FormData object
data.append('file', file, file.name);
// Create a new XMLHttpRequest
var xhr = new XMLHttpRequest();
// Post file data for upload
xhr.open('POST', 'upload.php', true);
xhr.send(data);
xhr.onload = function () {
// Get response and show the uploading status
var response = JSON.parse(xhr.responseText);
if(xhr.status === 200 && response.status == 'ok'){
$("#dropBox").html('<p class="success">File has been uploaded successfully. Click to upload another file.</p>');
}else if(response.status == 'type_err'){
$("#dropBox").html('<p class="error">File extension error! Click to upload another file.</p>');
}else{
$("#dropBox").html('<p class="error">Something went wrong, please try again.</p>');
}
};
}
}
}
</script>
Once the user selects a file, the file data is submitted to the upload.php
file for further processing with PHP.
This upload.php
file is loaded by the Ajax request to handle the file upload operations with PHP.
<?php
if(isset($_POST) == true){
// Generate unique file name
$fileName = time().'_'.basename($_FILES["file"]["name"]);
// File upload path
$targetDir = "uploads/";
$targetFilePath = $targetDir . $fileName;
// Allow certain file formats
$fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
$allowTypes = array('jpg', 'png', 'jpeg', 'gif', 'pdf');
if(in_array($fileType, $allowTypes)){
// Upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
// Insert file data into the database if needed
//........
// Success response
$response['status'] = 'ok';
}else{
$response['status'] = 'err';
}
}else{
$response['status'] = 'type_err';
}
// Render response data in JSON format
echo json_encode($response);
}
In this example code, we tried to show the Ajax file upload process as simple as possible. You can enhance the functionality of this script with advanced features, like image preview, progress bar, etc. However, you can go through the following tutorials for other possible methods to upload files in PHP.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
how can i upload files on click