Uploading a file without page refresh is a more user-friendly way than refreshing the whole page.
It allows displaying image preview instantly after upload.
You can upload single or multiple files using jQuery AJAX.
In this tutorial, I show how you can upload multiple image files and display preview after upload using jQuery AJAX and PHP.
Contents
1. HTML
Create a <form >
.
Add a file element and a button in it.
For enabling multiple file selection added multiple
attribute and name
as Array type (name='files[]'
).
Use <div id='preview'>
to show image preview using jQuery AJAX after successfully upload.
Completed Code
<style type="text/css"> #preview img{ margin: 5px; } </style> <form method='post' action='' enctype="multipart/form-data"> <input type="file" id='files' name="files[]" multiple><br> <input type="button" id="submit" value='Upload'> </form> <!-- Preview --> <div id='preview'></div>
2. Script
On upload button click create FormData()
object and count total files are been selected.
Loop on the selected files and append in form_data
.
Send AJAX POST request to ajaxfile.php
. Pass form_data
as data
, set dataType: 'json'
, contentType: false
, and processData: false
.
On AJAX successful callback loop on the response
to get the file path.
Append <img >
element in <div id='preview' >
where use src
variable in img
src
attribute.
Completed Code
$(document).ready(function(){ $('#submit').click(function(){ var form_data = new FormData(); // Read selected files var totalfiles = document.getElementById('files').files.length; for (var index = 0; index < totalfiles; index++) { form_data.append("files[]", document.getElementById('files').files[index]); } // AJAX request $.ajax({ url: 'ajaxfile.php', type: 'post', data: form_data, dataType: 'json', contentType: false, processData: false, success: function (response) { for(var index = 0; index < response.length; index++) { var src = response[index]; // Add img element in <div id='preview'> $('#preview').append('<img src="'+src+'" width="200px;" height="200px">'); } } }); }); });
3. PHP
Create an ajaxfile.php
file and a uploads
folder to store files.
Count total files, assign upload location to $upload_location
, and create a $files_arr
Array to store file path after file upload.
Loop on the files.
Initialize $valid_ext
Array with valid image extensions.
Check if the file extension exists in $valid_ext
Array. If exists then upload the file and initialize $files_arr
Array with $path
.
Return $files_arr
in JSON format for image preview.
Completed Code
<?php // Count total files $countfiles = count($_FILES['files']['name']); // Upload Location $upload_location = "uploads/"; // To store uploaded files path $files_arr = array(); // Loop all files for($index = 0;$index < $countfiles;$index++){ if(isset($_FILES['files']['name'][$index]) && $_FILES['files']['name'][$index] != ''){ // File name $filename = $_FILES['files']['name'][$index]; // Get extension $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION)); // Valid image extension $valid_ext = array("png","jpeg","jpg"); // Check extension if(in_array($ext, $valid_ext)){ // File path $path = $upload_location.$filename; // Upload file if(move_uploaded_file($_FILES['files']['tmp_name'][$index],$path)){ $files_arr[] = $path; } } } } echo json_encode($files_arr); die;
4. Output
5. Conclusion
In the example, I used jQuery AJAX for uploading image files only but you can allow other files upload by specifying file extension in $valid_ext
variable.
But you need to modify the file preview code.
If you found this tutorial helpful then don't forget to share.