Last updated on January 12th, 2023 at 10:14 am

Very simple and easy to implement file uploading script using HTML5. I am not using any API here and all I use is the jQuery library.

Table of Contents

Script Features & Techniques

  • Major portion is of jQuery along with Ajax to send request to the server side script (php)
  • Simple php code that will accept post action and move file to the server.
  • HTML form along with some div tag to create an area to drag and drop the files.
  • Manual file uploading is also available [Single File Upload]
  • No external API required
  • Displays number of files dropped in the div area using javascript.

Create HTML Form

First we need to create an html page with div tag and other details.

<div name="ulbox" id="ulbox" style="border: 5px dashed black; width: 800px; height: 200px;font-family: Times New Roman, Times, serif;color:#D3D3D3;font-size:70px;text-align:center">Upload Files Here
 </div><form enctype="multipart/form-data" id="uploadformid" method="post" action="upload.php">
<input type="file" name="files[]" multiple="multiple">
<input type="submit" value="submit">
</form>

The above code will create a dotted area div for dragging and dropping the files along with a regular file upload form option.

Add Jquery – Ajax

The next set of code is the jQuery library along with Ajax request to submit the files

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>                                                                              
<script type="text/javascript">
if (window.FormData === undefined) {
    alert("HTML5 Not Supported, Please Use Regular Uploading Method");
    }
    $(function () {
 
        var $box = $("#ulbox");
        $box.bind("dragenter", dragEnter);
 
        $box.bind("dragover", dragLeave);
        $box.bind("drop", drop);
 
        function dragEnter(evt) {
            evt.stopPropagation();
            evt.preventDefault();
            console.log("dragEnter...");
            $(evt.target).addClass('over');
            return false;
        }
        function dragLeave(evt) {
            evt.stopPropagation();
            evt.preventDefault();
            console.log("drag leave...");
            $(this).css('background-color', 'white');
            $(evt.target).removeClass('over');
            return false;
        }
 
 
        function drop(evt) {
            evt.stopPropagation();
            evt.preventDefault();
            $(evt.target).removeClass('over');
 
            var files = evt.originalEvent.dataTransfer.files;
 
document.getElementById('ulbox').innerHTML = 'Files Uploaded '+files.length;
 var uploadFormData = new FormData($("#uploadformid")[1]);
    if(files.length > 0) { // checks if any files were dropped
        for(f = 0; f < files.length; f++) { // for-loop for each file dropped
            uploadFormData.append("files[]",files[f]);  // adding every file to                                                                                         the form so you could upload multiple files
        }
    }
                    $.ajax({
                        type: "POST",
                        url: "upload.php",
                        //paramname: 'Filedata',
                        contentType: false,
                        processData: false,
                        data: uploadFormData,
                        success:function(ret)
        {
            //alert("Test"+ret);
        },
                    });
                }
 
 
         });
    </script>

Above Javascript initially calls jquery library. Then it checks whether browser supports HTML5 or not using window.FormData. If window.FormData is not defined then browser doesn’t support HTML5 file upload and the code will throw an error alerting the user to upload file using regular method. After window.FormData is checked we are using drag and drop elements of Jquery. Also i have added console log so if you have firebug for Mozilla installed you can see the log output in the console log. This will be good for troubleshooting. After that we are getting data from all files and appending the file data to uploadFormData variable.

Once all files are appended use Ajax to post details to the php file upload.php, Ajax request part looks like this

$.ajax({
                      type: "POST",
                      url: "upload.php",              
                      contentType: false,
                      processData: false,
                      data: uploadFormData,
                      success:function(ret)
      {
          //alert("Test"+ret);
      },
                  });

The success function has value returned from upload.php file. You can alert that value or update the main webpage with that value. This can be modified according to your requirement.

Add PHP Code

Now client set up is completed. We need to create a file (upload.php) with php code that will accept this Ajax post request and upload all the files to the defined location.

<?php
define("UPLOAD_DIR", "myuploadesfiles/");
$myFile = $_FILES["files"];
$number_of_files = count($_FILES["files"]["tmp_name"]);
$i=0;
for($i==0;$i<$number_of_files;$i++)
{
$success = move_uploaded_file($_FILES["files"]["tmp_name"][$i],UPLOAD_DIR.$_FILES["files"]["name"][$i]);
if (!$success) {
       echo "<p>Unable to save file.</p>";
       //exit;
    }
else
{
echo "File <b>".$_FILES["files"]["name"][$i]."</b> has been uploaded<br>";
}
}
?>

Files are uploaded to UPLOADS directory inside server.
We are counting the number of files uploaded using variable ‘i’
Variable $_FILES[“files”][“name”][$i] contains file names.

If upload process is successful then it will echo message to the user stating that file has been uploaded.

Complete Code

Please find the entire code below.

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>                                                                             
<script type="text/javascript">
if (window.FormData === undefined) {
    alert("HTML5 Not Supported, Please Use Regular Uploading Method");
    }
    $(function () {
  
        var $box = $("#ulbox");
        $box.bind("dragenter", dragEnter);
  
        $box.bind("dragover", dragLeave);
        $box.bind("drop", drop);
  
        function dragEnter(evt) {
            evt.stopPropagation();
            evt.preventDefault();
            console.log("dragEnter...");
            $(evt.target).addClass('over');
            return false;
        }
        function dragLeave(evt) {
            evt.stopPropagation();
            evt.preventDefault();
            console.log("drag leave...");
            $(this).css('background-color', 'white');
            $(evt.target).removeClass('over');
            return false;
        }
  
  
        function drop(evt) {
            evt.stopPropagation();
            evt.preventDefault();
            $(evt.target).removeClass('over');
  
            var files = evt.originalEvent.dataTransfer.files;
  
document.getElementById('ulbox').innerHTML = 'Files Uploaded '+files.length;
 var uploadFormData = new FormData($("#uploadformid")[1]);
    if(files.length > 0) { // checks if any files were dropped
        for(f = 0; f < files.length; f++) { // for-loop for each file dropped
            uploadFormData.append("files[]",files[f]);  // adding every file to the form so you could upload multiple files
        }
    }
                    $.ajax({
                        type: "POST",
                        url: "upload.php",
                        //paramname: 'Filedata',
                        contentType: false,
                        processData: false,
                        data: uploadFormData,
                        success:function(ret)
        {
            //alert("Test"+ret);
        },
                    });
                }
  
  
         });
    </script>
<div name="ulbox" id="ulbox" style="border: 5px dashed black; width: 800px; height: 200px;font-family: Times New Roman, Times, serif;color:#D3D3D3;font-size:70px;text-align:center">Upload Files Here
 </div><form enctype="multipart/form-data" id="uploadformid" method="post" action="upload.php">
<input type="file" name="files[]" multiple="multiple">
<input type="submit" value="submit">
</form>

DEMO

Check out our simple script to upload files to server using just PHP, without much complexity How to upload | download file using PHP

Leave a Reply

Your email address will not be published. Required fields are marked *