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.
Table of Content
- 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
.
Explore our tutorial on uploading multiple files using jQuery AJAX. Alternatively, check out our guide on uploading a file directly to the database.
For a comprehensive understanding of displaying dynamic progress bar during file uploads, you can also refer to this tutorial.
If you found this tutorial helpful then don't forget to share.
Thanks for this good how-to.
After some hours of search on the net this article has resolved all my problems 🙂
Thank you! It was very useful!
This is an awesome article, after days of efforts, this was the best solution I found
this post is great but i want to sent data also. how i send data and image at the same time?
Append data in FormData object.
Example –
On the AJAX file read it using $_POST[‘name’].
not working
Hi Sunil,
Have you check browser console is any error displaying?
Well Thanx for the codes the thing is that I just want to send only single image and m getting the error- Cannot read property ‘file’ of null I dont want to save multiple images i just need only one image
Hi Abhinav,
In the example, I am already saving a single file.
Thank you very much Mr. Yogesh Singh. It works, I tried modify the code to upload image and video file but it us not working. Please I need your help…
Thanks Yogesh Singh for your recommendations clear and works fine
You’re welcome.
Hi Yogesh, nice tutorial there, but it’s not working for me.
Console throws an error ,”append called on an object that does not implement interface FormData”
Hi Joseph,
Can you share me your code at makitweb@gmail.com so I can check it?
This works really nicely. How would I go about uploading multiple files from a single input field? (E.g., ) When I try, it only keeps the data for the last image in the list.
I tried looping through the files, but to no avail. I had replaced these lines:
var files = $(‘#$input_id’)[0].files[0];
formData.append(‘file’,files);
with:
$.each($(‘#file’)[0].files, function(i, file) {
fd.append(‘file’, file);
});
and:
var upl = $(‘#file’).files.length;
for (var x = 0; x < upl; x++) {
fd.append('file', $('#file').files[x]);
}
But only the last image in the list would be saved to FormData. Any ideas?
fd.append(‘file[]’ , ……)
I figured a way to allow multiple uploads from a single input field:
Replace:
var files = $(‘#file’)[0].files[0];
fd.append(‘file’,files);
with this:
var input = $(‘#file’)[0];
$.each(input.files, function(i, file) {
// add each file to ‘files’ element in
fd.append(‘files[]’, file);
});
$.each() runs through each of the files selected in the field. Make sure you’ve set a key name with “[]” so it will accept multiple files.
That’s great you figure out on your own. I will try to publish a tutorial on this topic soon.
please using Jquery, how do i send the image and another parameter e.g an ID
how do i pass another parameter with the image using jquery please
Hi Peter,
You need to append data in FormData object.
Example –
fd.append(‘ID’,121);
On the AJAX file read it using $_POST[‘ID’].
it didnt work Yogesh Singh. i am having trouble passing a new name for the file
Hi Yogesh Singh
Thank so much ! It’s perfectly clear !
Thanks agani and have a nice day !!
Laurent
You’re welcome.
I am getting the following error:
Access to XMLHttpRequest at ‘url here’ from origin ‘http://127.0.0.1:5501’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
Hi Varun,
What is your HTML form page URL?
thank you! really saved my time. cheers!!!
You’re welcome.
Hii
i have code like this i am binding ajax response to a table but i had a image tag how i bind data form ajax to direct in Src of that image (Please check var ntd in the code)
my code is like this
for (var i = 0; i < data.length; i++) {
if (data[i].invoicedetails != "") {
var td = '’ + data[i].Sno + ” + data[i].Name + ” + data[i].Nature + ” + data[i].AnimalCr + ” + data[i].Kismat + ” + data[i].Extra + ”
tr += “” + td + “”;
tr += ” Image”;
// var ntd = “‘”
var ntd = “‘”
tr += “” + ntd + “”;
}
}
this a tr that im appending in above code (Please check var ntd in the code)
Can src of this image can be bind like this currently it not working
i can do it by selector but is want like this
var ntd = “‘”
tr += “” + ntd + “”;
How to send data also with image in modal form
How could I upload the file along with other data using json like:
$.ajax({
url: ‘upload.php’,
type: ‘post’,
data: {
data1: …,
data2: …,
file: …,
},
contentType: json,
success: function(response){
if(response != 0){
$(“#img”).attr(“src”,response);
$(“.preview img”).show(); // Display image element
}else{
alert(‘file not uploaded’);
}
},
});
Hi Neo,
If you want to pass data with the file then append the value in the FormData object.
Example – fd.append(‘name’,name); fd.append(‘age’,age);
Here’s an example: https://stackoverflow.com/questions/5392344/sending-multipart-formdata-with-jquery-ajax#answer-5976031
very good, terimakasih
Curious what has to be changed in the code to make it work for video, like MP4. I added that as a valid extension and it doesn’t work. And also wonder why the default image doesn’t show. Doesn’t for me, and doesn’t show in your video. Thanks BTW for the great tutorial.
Hi Mike,
You need to specify video file extensions in the $valid_extensions Array. Have you checked php.ini post_max_size and upload_max_filesize values. File will not upload if file size exceed defined max size. You can view this tutorial for reference. Image preview only show if image file successfully uploaded.
Hi Yogesh,
Very nice tutorial and really the easyest in the Internet.
But how can i achieve that the picture is previewed before i upload it like in your video?
And cool that you still make suport 2 years later.
Thanks very much Mr. Yogesh Singh for the simplified code. What if I want to upload both image file and video file using the same method you used above. Image alone works but uploading with videos returns ‘undefine file index’ errors
HEY MAN! THANKS YOU FOR IT’S BEUTY CODE!!! I LOVE YOU!!!))))
You’re welcome.
Hi! How would I send the image as attachment to email using mail() in php?
Oh God I wish i had enough words to thank you brother.Thank you so much.This was what I was looking for the whole time
I’m glad you found it useful.
Thanks it is really helpfull
You’re welcome.
Hi Yogesh,
Great Tutorial but when I run i get the following error?
index.html:33 Uncaught ReferenceError: jQuery is not defined
at index.html:33
Kind regards
Jonathan
Thank you soo much.. it was really helpful.. god bless you
You’re welcome.
Thank You Buddy ,
It was very use full to me awesome work
You’re welcome.
Good Job.
Question: How to validate this :
$filename = $_FILES[‘file’][‘name’]; in case not image selected when i click button upload
Hi Edgar,
I updated the tutorial to check if the file selected or not with Javascript and PHP.
You are the best..
Thank you so much, bro..
I’m from Indonesia..
God Bless you..
Hello Sir,
By using the code I am able to upload the file and return the image name(It is showing in the network tab), but could not able to get it in the ajax response. Instead of image name it’s printing some HTML code :(, please help me it’s a bit urgent for me.
Here are some corrections By using the code I am able to upload the file and return the image name, but Instead of the only image name, it’s printing some HTML code and then showing the image name :(, please help me it’s a bit urgent for me., I have sent you my code with a screenshot in the email.
var formData = new FormData();
formData.append(“file”, file);
This is giving me the formdata as {} even though file exists.
Thank you, this actualyl works right out of the box! Love it
You’re welcome.
Thanks for the great how-to blog post…
This line here:
fd.append(‘file’,files[0]);
in particular the files[0]
solved my issue…
Great article!
Do this for cgi python please