Create Web Form with Drag and Drop File Upload using JavaScript and PHP

The web form is a commonly used element in each website. In some cases, the user is allowed to select files with the input data so that the files are attached to the form data. Mostly the default HTML file input interface is used to select and upload files. But if you want to make web form UI more effective, drag and drop file upload feature can be used. The drag-and-drop feature provides an advanced file upload interface on the web page. The user can drag the files from the local drive and drop them into the DOM element. In this tutorial, we will show you how to create web form with drag & drop file upload and submit form data with multiple files using JavaScript.

DropzoneJS library provides an effective solution to integrate drag and drop file upload feature in HTML with JavaScript. In this example script, we integrate drag-and-drop file upload in web form using JavaScript and upload multiple attachment files with form data with PHP.

The following steps will be followed to implement the drag and drop file upload with form data submission using JavaScript and PHP.

  • Create an HTML form with input elements.
  • Define a droppable element to select multiple files from the computer.
  • Combine form data with files and submit to the server-side script using JavaScript.
  • Upload multiple files and insert form data in the database using PHP.

Before getting started, take a look at the file structure of drag & drop file upload with form data using JavaScript and PHP.

web_form_with_drag_drop_file_upload/
├── index.html
├── dbConfig.php
├── submit.php
├── uploads/
└── js/
    ├── dropzone.min.js
    └── dropzone.min.css

Create Database Table

To store the form data and file info, a table is required in the database. The following SQL creates a form_data table with some required fields in the MySQL database.

CREATE TABLE `form_data` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `email` varchar(50) NOT NULL,
  `attachments` varchar(255) DEFAULT NULL COMMENT 'Files names in comma separated string',
  `submitted_on` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Configuration (dbConfig.php)

The dbConfig.php file is used to connect and select the database using PHP and MySQL. Specify the database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName) as per your database credentials.

<?php 
// Database configuration
$dbHost     "localhost";
$dbUsername "root";
$dbPassword "root";
$dbName     "codexworld_db";

// Create database connection
$db = new mysqli($dbHost$dbUsername$dbPassword$dbName);

// Check connection
if ($db->connect_error) {
    die(
"Connection failed: " $db->connect_error);
}
?>

Web Form with Drag and Drop File Upload (index.html)

Include the DropzoneJS library files to enable the drag and drop file upload functionality.

<script src="js/dropzone/dropzone.min.js"></script>
<link href="js/dropzone/dropzone.min.css" rel="stylesheet" type="text/css" />

Create an HTML form with enctype="multipart/form-data".

  • Define an input elements and dropzone element where the drag&drop file upload feature will be attached.
<div class="wrapper">
    <!-- Status message -->
    <div id="statusMsg"></div>
    
    <!-- File upload form -->
    <div class="col-lg-12">
        <form id="fupForm" enctype="multipart/form-data">
            <div class="form-group">
                <label for="name">Name:</label>
                <input type="text" class="form-control" id="name" placeholder="Enter name" />
            </div>
            <div class="form-group">
            <label for="email">Email:</label>
                <input type="email" class="form-control" id="email" placeholder="Enter email" />
            </div>
            <div class="form-group">
                <label for="file">Attachments:</label>
                <!-- drag&drop upload section -->
                <div class="dropzone">
                    <div class="dz-message">
                        Drag and drop files here or click to select.
                    </div>
                </div>
            </div>
            
            <button type="submit" id="submitBtn" class="btn btn-primary">Submit</button>
        </form>
    </div>
</div>

The following JavaScript code is used to attach the drag and drop file upload feature to the webform and process the form submission with multiple files.

  • Initialize the Dropzone object and define configuration options.
  • Disable auto queue process in Dropzone.
  • Start Dropzone queue process on button click.
  • Use sendingmultiple method with the FormData object to combine form data with files.
  • Use successmultiple method to get the response from the server-side script and display the form submission status.
<script>
//Disabling autoDiscover
Dropzone.autoDiscover = false;

// Dropzone has been added as a global variable.
var myDropzone = new Dropzone(".dropzone", {
    url: "submit.php",
    paramName: "file",
    autoProcessQueue: false,
    addRemoveLinks: true,
    uploadMultiple: true,
    maxFilesize: 2,
    maxFiles: 10,
    parallelUploads: 10,
    acceptedFiles: "image/*,application/pdf,.doc,.docx",

    // The setting up of the dropzone
    init: function() {
        var myDropzone = this;

        // First change the button to actually tell Dropzone to process the queue.
        //this.element.querySelector("#submitBtn").addEventListener("click", function(e) {
        document.querySelector("#submitBtn").addEventListener("click", function(e) {
            // Make sure that the form isn't actually being sent.
            e.preventDefault();
            e.stopPropagation();

            if (myDropzone.getQueuedFiles().length > 0) {                        
                myDropzone.processQueue();  
            } else {
                var blob = new Blob();
                blob.upload = { 'chunked': myDropzone.options.chunking };
                myDropzone.uploadFile(blob);
            } 
        });

        // Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
        // of the sending event because uploadMultiple is set to true.
        this.on("sendingmultiple", function(file, xhr, formData) {
            // Gets triggered when the form is actually being sent.
            // Hide the success button or the complete form.
            formData.append("name", document.getElementById("name").value);
            formData.append("email", document.getElementById("email").value);
            formData.append("submit", 1);
        });
        this.on("successmultiple", function(files, response) {
            // Gets triggered when the files have successfully been sent.
            // Redirect user or notify of success.
            let response_jsn = JSON.parse(response);

            if(response_jsn.status == 1){
                document.getElementById("fupForm").reset();
                myDropzone.removeAllFiles(true); 
                document.querySelector('#statusMsg').innerHTML = '<p class="alert alert-success">'+response_jsn.message+'</p>';
            }else{
                document.querySelector('#statusMsg').innerHTML = '<p class="alert alert-danger">'+response_jsn.message+'</p>';
            }
            
            // Auto-hide alert message
            setTimeout(function() {
                document.querySelector('.alert').remove();
            }, 5000);
        });
        this.on("errormultiple", function(files, response) {
            // Gets triggered when there was an error sending the files.
            // Maybe show form again, and notify user of error
            document.querySelector('#statusMsg').innerHTML = '<p class="alert alert-danger">'+response+'</p>';
        });
    }
});    
</script>

Upload Multiple Files and Insert Form Data (submit.php)

The following code handles the multiple file upload and form data submission functionality.

  • Retrieve the form field data using the PHP $_POST method.
  • Retrieve the multiple files data using the PHP $_FILES method.
  • Validate input fields to check whether the mandatory fields are empty.
  • Validate email address using FILTER_VALIDATE_EMAIL in PHP.
  • Check the file extension to allow certain file formats (Image, PDF, and MS Word) to upload.
  • Upload files to the server using PHP move_uploaded_file() function.
  • Insert web form data and file names in the database using PHP & MySQL.
  • Return response to the successmultiple callback of the dropzone class.
<?php 

// Include the database config file 
include_once 'dbConfig.php'

// File upload folder
$uploadDir 'uploads/';

// Allowed file types
$allowTypes = array('pdf''doc''docx''jpg''png''jpeg');

// Default response
$response = array(
    
'status' => 0,
    
'message' => 'Form submission failed, please try again.'
);


// If form is submitted
$valErr '';
if(isset(
$_POST['submit'])){
    
// Get the submitted form data
    
$name $_POST['name'];
    
$email $_POST['email'];

    
// Check whether submitted data is not empty
    
if(empty($name)){
        
$valErr .= '<br/>Please enter your name.'
    }
    if(empty(
$email) || filter_var($emailFILTER_VALIDATE_EMAIL) === false){
        
$valErr .= '<br/>Please enter a valid email.'
    }

    
// Process input data and file upload
    
if(empty($valErr)){
        
$fileNames array_filter($_FILES['file']['name']); 
         
        
// Upload multiple files
        
$uploadStatus 1;
        
$uploadedFile ''
        if(!empty(
$fileNames)){ 
            foreach(
$_FILES['file']['name'] as $key=>$val){  
                
// Set file upload path
                
$fileName basename($_FILES['file']['name'][$key]);  
                
$targetFilePath $uploadDir $fileName;  
                
                
// Check whether file data is valid
                
if($fileName != 'blob'){
                    
// Check whether the selected file type is allowed to upload
                    
$fileType pathinfo($targetFilePathPATHINFO_EXTENSION);  
                    if(
in_array($fileType$allowTypes)){  
                        
// Upload file to server  
                        
if(move_uploaded_file($_FILES['file']["tmp_name"][$key], $targetFilePath)){  
                            
$uploadedFile .= $fileName.','
                        }else{  
                            
$uploadStatus 0
                            
$response['message'] = 'Sorry, there was an error uploading your file.'
                        }  
                    }else{  
                        
$uploadStatus 0
                        
$response['message'] = 'Sorry, only '.implode('/'$allowTypes).' files are allowed to upload.'
                    }
                }
            }  
        } 

        if(
$uploadStatus == 1){ 
            
$uploadedFileStr trim($uploadedFile','); 

            
// Insert form data in the database
            
$sqlQ "INSERT INTO form_data (name,email,attachments,submitted_on) VALUES (?,?,?,NOW())";
            
$stmt $db->prepare($sqlQ);
            
$stmt->bind_param("sss"$name$email$uploadedFileStr);
            
$insert $stmt->execute();
             
            if(
$insert){ 
                
$response['status'] = 1
                
$response['message'] = 'Form data and attachment files are submitted successfully!'
            } 
        }
    }else{
        
$response['message'] = 'Please fill all the mandatory fields!'.$valErr;
    }
}

// Return response
echo json_encode($response);

?>

PHP Contact Form with Google reCAPTCHA

Conclusion

This example code helps you to build a web form with drag-and-drop file upload in the website using JavaScript. You can allow the user to upload multiple files and submit attachments with input form data. The drag&drop file upload and form submission functionality is handled without page refresh using JavaScript.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

Leave a reply

keyboard_double_arrow_up