Multiple file upload using jquery and php

In this tutorial I’m going to show you how you can handle multiple file uploads using php and jquery.

 

Requirements

 

I’m assuming that you already know the basics of php and jquery. I’ll try to make this tutorial as short as possible. But you can also check out the documentation of the blueImp jquery file upload if you are pretty confident in your skills.

First, you need to include the css files for the file upload plugin. Remember to change the code inside the href attribute to match your folder structure.

<link rel="stylesheet" href="../jqui.css" id="theme">
<link rel="stylesheet" href="../jquery.fileupload-ui.css">

Then the html form that will be used to upload files. Remember that this can be used to upload multiple files to the webserver.

<form id="file_upload" action="upload.php" method="POST" enctype="multipart/form-data">
    <input type="file" name="file" multiple>
    <button>Upload</button>
    <div>Upload files</div>
    
</form>

Then just after the form. Insert a table tag. This will be used later on to display the selected files.

<table id="files"></table>

Next, include the scripts you downloaded earlier.

<script src="../jq.js"></script>
<script src="../jqui.js"></script>
 
<script src="../jquery.fileupload.js"></script>
<script src="../jquery.fileupload-ui.js"></script>

Then insert another script tag. This script will communicate with ‘upload.php’. And you can also define here  some rules regarding filesize , filetype and other restrictions in uploading a file.

<script>
/*global $ */
$(function () {
    $('#file_upload').fileUploadUI({
        uploadTable: $('#files'),
        downloadTable: $('#files'),
        buildUploadRow: function (files, index) {
            return $('<tr><td>' + files[index].name + '</td>' +
                    '<td class="file_upload_progress"><div></div></td>' +
                    '<td class="file_upload_cancel">' +
                    '<button class="ui-state-default ui-corner-all" title="Cancel">' +
                    '<span class="ui-icon ui-icon-cancel">Cancel</span>' +
                    '</button></td></tr>');
        },
        buildDownloadRow: function (file) {
            return $('<tr><td>' + file.name + '</td></tr>');
        }
});
);
</script>

That’s pretty much what you need if you don’t need to restrict the user from uploading a 200TB file. Or a javascript file that will mess up your whole system.

If however you want to limit the user from doing that. Then include the function below. Under the beforeSend event. The code below will limit the file size to 1Mb or 1 Million Bytes? Yeah, that’s a question mark since I’m not sure if 1Mb is really equal to 1 Million Bytes.

 function (event, files, index, xhr, handler, callBack) {
         if (files[index].size > 1000000) {
             handler.uploadRow.find('.file_upload_progress').html('FILE TOO BIG!');
             setTimeout(function () {
                 handler.removeNode(handler.uploadRow);
             }, 10000);
             return;
         }
         
         
        
         callBack();
 }

If you’re not satisfied with just limiting the file size. And you want the user to be able to upload only specific file types. Like for example, images:

var regexp = /.(png)|(jpg)|(gif)$/i;
      
       if (!regexp.test(files[index].name)) {
           handler.uploadRow.find('.file_upload_progress').html('ONLY IMAGES ALLOWED!');
           setTimeout(function () {
               handler.removeNode(handler.uploadRow);
           }, 10000);
           return;
 }

Lastly, the php script that will do the transfer from the clients computer to a folder inside the webservers web accessible directory. Here’s a short story on how this works: First the user will click on the upload button. Then selects multiple files. Blue Imp Jquery File Uploader will handle all the processes needed to forward the file information (temporary file path, filename, file size, file type) to the php script that you defined. In this case ‘upload.php’. As you can see from the code below. We don’t even have to create an array for all the files that are selected since its already done by Blue Imp. As you can see, the selected files will be uploaded to a folder named ‘img’. We used the ‘move_uploaded_file’ function because the file is not being materialized directly to the folder where we want it to reside. After every upload, it first resides on a ‘tmp’ or temporary folder in your webserver. In wamp the temporary folder is in: ’ C:wamptmp’ . You might notice that all the files in that folder have .tmp file extension and that the filename is mainly composed of unusual characters. That is why we need to issue this ‘$_FILES[“file”][“name”]’ as a parameter to get the original filename.

<?php
 
$file = $_FILES['file'];
echo '{"name":"'.$file['name'].'","type":"'.$file['type'].'","size":"'.$file['size'].'"}';
 
 
$tempath=$_FILES["file"]["tmp_name"];
$transform=explode('.', $tempath);
 
 
$truefile=explode('.', $_FILES["file"]["name"]);
$filenamepath=$transform[0]. ".". $truefile[1];
 
move_uploaded_file($_FILES["file"]["tmp_name"],
      "img/" . $_FILES["file"]["name"]);
?>

This is what it will look like. If you haven’t customized it.

image

Notice that it didn’t actually upload the txt file, and the mkv file which is 70Mb in size. But one thing that has caught my attention is the txt file which I changed the file extension to png. It actually uploaded it. I wonder if its really possible to detect the real extension of a file noting that the extension was only edited.

image

 

Conclusion

That is all with this tutorial. I hope you learned something. And please share this site using the buttons below if this tutorial has helped you.

7 thoughts on “Multiple file upload using jquery and php

  1. Pingback: Introduction to premium tutorials « Data Integrated Entity

  2. Howdy would you mind stating which blog platform you’re working with?

    I’m planning to start my own blog soon but I’m having a difficult time selecting between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your design and style seems different then most blogs and I’m looking for something
    completely unique. P.S Apologies for being off-topic but I had to
    ask!

Leave a reply to Emanuel Cancel reply