Uploading the files to a server is a common task in web development.
In PHP you can easily upload any type of file on the server using the move_uploaded_file() method. But it requires a form to be submitted for uploading the selected file.
You can make this process smoother with jQuery AJAX, it also improves user experience. You can directly display the image or file preview after it is been uploaded or alert an error if file is not validated without reloading the page.
For this FormData
object is use to pass the selected file to the server using AJAX.
In this tutorial, you’ll learn step-by-step how to use PHP jQuery, and AJAX to upload files with validation and display its preview.
Contents
- Create an HTML Form for File Uploads
- Define the Upload PHP Script
- Add jQuery and Ajax to Handle File Uploads
- Output
- Conclusion
1. Create an HTML Form for File Uploads
Create file element and a button. For file preview create <img >
and <a >
element. Element gets show/hide for preview after file successfully upload using jQuery.
Completed Code
<div > <div > <input type="file" id="file" name="file" /> <input type="button" class="button" value="Upload" id="but_upload"> </div> <!-- File Preview --> <div style="margin-top: 40px;" > <!-- Image --> <img src="" class="prevel" id="imgprev" width="300" style="display: none;" > <!-- Non-image --> <a href="#" target="_blank" class="prevel" id="fileprev" style="display: none;">View File</a> </div> </div>
2. Define the Upload PHP Script
Create an upload.php
file and upload
folder to store image files.
Read file extension, initialized $allowed_extensions
Array with allowed file extensions – “jpg”,”jpeg”,”png”,”pdf”,”docx”.
Check if file extension exists in $allowed_extensions
Array or not. If exists then assign 1
to $status
, file location to $response['path']
variable, and extension to $response['extension']
.
Return $response
Array in JSON format.
Completed Code
<?php if(isset($_FILES['file']['name'])){ /* Getting file name */ $filename = $_FILES['file']['name']; /* Location */ $location = "upload/".$filename; /* Extension */ $extension = pathinfo($location,PATHINFO_EXTENSION); $extension = strtolower($extension); /* Allowed file extensions */ $allowed_extensions = array("jpg","jpeg","png","pdf","docx"); $response = array(); $status = 0; /* Check file extension */ if(in_array(strtolower($extension), $allowed_extensions)) { /* Upload file */ if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){ $status = 1; $response['path'] = $location; $response['extension'] = $extension; } } $response['status'] = $status; echo json_encode($response); exit; } echo 0;
3. Add jQuery and Ajax to Handle File Uploads
Now that your HTML form is set up, it’s time to add some jQuery and Ajax code to enable file uploads.
Add click
event on the upload button. When it gets clicked then read the selected file and create a FormData
object.
Check if a file is selected or not. If not selected then alert("Please select a file.")
otherwise, append files[0]
to 'file'
key in fd
.
Send an AJAX request where pass the fd
object as data and on successful callback check the response.status
is 1
or not. If it is 1
means file is successfully uploaded and display preview.
If file extension is pdf or docx then update <a id="fileprev">
href
attribute the file path otherwise update <img id="imgprev">
src
attribute.
Completed Code
$(document).ready(function(){ $("#but_upload").click(function(){ var fd = new FormData(); var files = $('#file')[0].files; // Check file selected or not if(files.length > 0 ){ fd.append('file',files[0]); $.ajax({ url:'upload.php', type:'post', data:fd, dataType: 'json', contentType: false, processData: false, success:function(response){ if(response.status == 1){ var extension = response.extension; var path = response.path; $('.prevel').hide(); if(extension == 'pdf' || extension == 'docx'){ $("#fileprev").attr("href",path); $("#fileprev").show(); }else{ $("#imgprev").attr("src",path); $("#imgprev").show(); } }else{ alert('File not uploaded'); } } }); }else{ alert("Please select a file."); } }); });
4. Output
5. Conclusion
By following the above steps you can easily upload image or document file and display its preview after upload. Not required to create <form >
when using AJAX for file upload, it will work whether the file element is created inside the <form >
or not.
Using FormData
object to store the file and pass in the AJAX request to upload it. With this, you can pass also additional information with file like – username, userid, new filename, etc. For this, you need to append it in FormData
object similar to file – fd.append('filename','newfilename');
.
In the PHP file access the file using $_FILES
. If you passed other data then access it using $_POST
.
You can view this tutorial to know how to upload multiple files using jQuery AJAX or you can also view this tutorial to upload file to the database.
If you found this tutorial helpful then don't forget to share.