I have already written a similar post long back using jQuery form Plugin if you wish you can see the link below:
Before going through the script you can see the demo here:
The difference between the above and this post is, here we are using pure jQuery no plugin used, also with a progress bar.
And the backend script is obviously PHP and there is one more different, this script can be used to upload images, documents, etc.,
Let’s see the Front end script first (HTML and jQuery also used Bootstrap for progress bar):
<!DOCTYPE html> <html> <head> <title>jQuery Ajax file upload with percentage progress bar</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- include jQuery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <!-- include bootstrap files --> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <script> $(function () { $('#btn').click(function () { $('.myprogress').css('width', '0'); $('.msg').text(''); var filename = $('#filename').val(); var myfile = $('#myfile').val(); if (filename == '' || myfile == '') { alert('Please enter file name and select file'); return; } var formData = new FormData(); formData.append('myfile', $('#myfile')[0].files[0]); formData.append('filename', filename); $('#btn').attr('disabled', 'disabled'); $('.msg').text('Uploading in progress...'); $.ajax({ url: 'uploadscript.php', data: formData, processData: false, contentType: false, type: 'POST', // this part is progress bar xhr: function () { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener("progress", function (evt) { if (evt.lengthComputable) { var percentComplete = evt.loaded / evt.total; percentComplete = parseInt(percentComplete * 100); $('.myprogress').text(percentComplete + '%'); $('.myprogress').css('width', percentComplete + '%'); } }, false); return xhr; }, success: function (data) { $('.msg').text(data); $('#btn').removeAttr('disabled'); } }); }); }); </script> </head> <body> <div class="container"> <div class="row"> <h3>jQuery Ajax file upload with percentage progress bar</h3> <form id="myform" method="post"> <div class="form-group"> <label>Enter the file name: </label> <input class="form-control" type="text" id="filename" /> </div> <div class="form-group"> <label>Select file: </label> <input class="form-control" type="file" id="myfile" /> </div> <div class="form-group"> <div class="progress"> <div class="progress-bar progress-bar-success myprogress" role="progressbar" style="width:0%">0%</div> </div> <div class="msg"></div> </div> <input type="button" id="btn" class="btn-success" value="Upload" /> </form> </div> </div> </body> </html>
As you can see I have used FormData() to send the form data to the backend PHP script.
Let’s see the PHP script as well:
<?php error_reporting(0); if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") { $path = "uploads/"; //set your folder path //set the valid file extensions $valid_formats = array("jpg", "png", "gif", "bmp", "jpeg", "GIF", "JPG", "PNG", "doc", "txt", "docx", "pdf", "xls", "xlsx"); //add the formats you want to upload $name = $_FILES['myfile']['name']; //get the name of the file $size = $_FILES['myfile']['size']; //get the size of the file if (strlen($name)) { //check if the file is selected or cancelled after pressing the browse button. list($txt, $ext) = explode(".", $name); //extract the name and extension of the file if (in_array($ext, $valid_formats)) { //if the file is valid go on. if ($size < 2098888) { // check if the file size is more than 2 mb $file_name = $_POST['filename']; //get the file name $tmp = $_FILES['myfile']['tmp_name']; if (move_uploaded_file($tmp, $path . $file_name.'.'.$ext)) { //check if it the file move successfully. echo "File uploaded successfully!!"; } else { echo "failed"; } } else { echo "File size max 2 MB"; } } else { echo "Invalid file format.."; } } else { echo "Please select a file..!"; } exit; }
You can read the comments in the above file to understand the script.
Download this script from the links below:
Hi, thanks for this post i’ve tested in my php application and it works really well. I’m trying to add sweet alert popup for error messages like “File size max 2 MB” etc, could you help me please?
thanks worked like a charm in one go .
Thank you, had problem with Serialize and file uploade for a while. Helpefull article.
Perfect its working fine in core PHP. Can you also please provide me the files in CodeIgniter? I try to integrate with CodeIgniter and it’s not working at there. Please help
Very nice code!
Thanks for this code. I was struggling with the ajax call to get a progressbar. This code works perfectly with CodeIgniter!
This is an excellent and clear option. Thank you so much for sharing.
very nice and perfact solution
Use “alert” in place of “echo”
There are 2 different technologies are used in this script PHP and JavaScript so ‘echo’ is used on PHP script, please go through the script so you can understand.