Skip to content

Instantly share code, notes, and snippets.

@kreativan
Last active February 11, 2024 12:17
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save kreativan/83febc214d923eea34cc6f557e89f26c to your computer and use it in GitHub Desktop.
Save kreativan/83febc214d923eea34cc6f557e89f26c to your computer and use it in GitHub Desktop.
Upload files with dropzone.js and php
<?php
// process $_POST request
if(isset($_POST["submitDropzone"])) {
// Do something
print_r($_POST);
}
?>
<form id="dropzone-form" action="./" method="POST" enctype="multipart/form-data">
<div class="uk-margin">
<input class="uk-input" type="text" name="name" palceholder="Name" />
</div>
<div class="uk-margin">
<input class="uk-input" type="email" name="email" palceholder="Email Address" />
</div>
<div id="dropzone" class="dropzone"></div>
<div class="uk-margin-top">
<input id="submit-dropzone" class="uk-button uk-button-primary" type="submit" name="submitDropzone" value="Submit" />
</div>
</form>
<link rel="stylesheet" href="dropzone.min.css">
<script src="dropzone.min.js"></script>
<script src="my-dropzone.js"></script>
// disable autodiscover
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("#dropzone", {
url: "upload.php",
method: "POST",
paramName: "file",
autoProcessQueue : false,
acceptedFiles: "image/*",
maxFiles: 5,
maxFilesize: 0.3, // MB
uploadMultiple: true,
parallelUploads: 100, // use it with uploadMultiple
createImageThumbnails: true,
thumbnailWidth: 120,
thumbnailHeight: 120,
addRemoveLinks: true,
timeout: 180000,
dictRemoveFileConfirmation: "Are you Sure?", // ask before removing file
// Language Strings
dictFileTooBig: "File is to big ({{filesize}}mb). Max allowed file size is {{maxFilesize}}mb",
dictInvalidFileType: "Invalid File Type",
dictCancelUpload: "Cancel",
dictRemoveFile: "Remove",
dictMaxFilesExceeded: "Only {{maxFiles}} files are allowed",
dictDefaultMessage: "Drop files here to upload",
});
myDropzone.on("addedfile", function(file) {
//console.log(file);
});
myDropzone.on("removedfile", function(file) {
// console.log(file);
});
// Add mmore data to send along with the file as POST data. (optional)
myDropzone.on("sending", function(file, xhr, formData) {
formData.append("dropzone", "1"); // $_POST["dropzone"]
});
myDropzone.on("error", function(file, response) {
console.log(response);
});
// on success
myDropzone.on("successmultiple", function(file, response) {
// get response from successful ajax request
console.log(response);
// submit the form after images upload
// (if u want yo submit rest of the inputs in the form)
document.getElementById("dropzone-form").submit();
});
/**
* Add existing images to the dropzone
* @var images
*
*/
var images = [
{name:"image_1.jpg", url: "example/image1.jpg", size: "12345"},
{name:"image_2.jpg", url: "example/image2.jpg", size: "12345"},
{name:"image_2.jpg", url: "example/image2.jpg", size: "12345"},
]
for(let i = 0; i < images.length; i++) {
let img = images[i];
//console.log(img.url);
// Create the mock file:
var mockFile = {name: img.name, size: img.size, url: img.url};
// Call the default addedfile event handler
myDropzone.emit("addedfile", mockFile);
// And optionally show the thumbnail of the file:
myDropzone.emit("thumbnail", mockFile, img.url);
// Make sure that there is no progress bar, etc...
myDropzone.emit("complete", mockFile);
// If you use the maxFiles option, make sure you adjust it to the
// correct amount:
var existingFileCount = 1; // The number of files already uploaded
myDropzone.options.maxFiles = myDropzone.options.maxFiles - existingFileCount;
}
// button trigger for processingQueue
var submitDropzone = document.getElementById("submit-dropzone");
submitDropzone.addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
if (myDropzone.files != "") {
// console.log(myDropzone.files);
myDropzone.processQueue();
} else {
// if no file submit the form
document.getElementById("dropzone-form").submit();
}
});
<?php
// define absolute folder path
$dest_folder = 'ABSOLUTE_FOLDER_PATH/';
if (!empty($_FILES)) {
// if dest folder doesen't exists, create it
if(!file_exists($dest_folder) && !is_dir($dest_folder)) mkdir($dest_folder);
/**
* Single File
* uploadMultiple = false
* @var $_FILES['file']['tmp_name'] string, file_name
*/
// $tempFile = $_FILES['file']['tmp_name'];
// $targetFile = $dest_folder . $_FILES['file']['name'];
// move_uploaded_file($tempFile,$targetFile);
/**
* Multiple Files
* uploadMultiple = true
* @var $_FILES['file']['tmp_name'] array
*
*/
foreach($_FILES['file']['tmp_name'] as $key => $value) {
$tempFile = $_FILES['file']['tmp_name'][$key];
$targetFile = $dest_folder. $_FILES['file']['name'][$key];
move_uploaded_file($tempFile,$targetFile);
}
/**
* Response
* return json response to the dropzone
* @var data array
*/
$data = [
"file" => $_POST["file"],
"dropzone" => $_POST["dropzone"],
];
header('Content-type: application/json');
echo json_encode($data);
exit();
}
@PkLearning
Copy link

thank you @kreativan it's useful!
now i try to get a name of file upload
can i get the name file passing $_POST?
when i print_r($_POST); it show only value in form

@kreativan
Copy link
Author

kreativan commented Mar 30, 2019

thank you @kreativan it's useful!
now i try to get a name of file upload
can i get the name file passing $_POST?
when i print_r($_POST); it show only value in form

No, you cant access file related data after form submit. In this case print_r($_POST); gives u only rest of the form fields, but not the file, because file is sent and processed with ajax request.
But you can have access and preview $_POST data as a callback response from php (see uplaod.php).
In this case form is submitted right after file upload, and page is reloaded, so you miss the ajax response from php.

U can disable form submit after upload, so you can preview and test $_POST data as response in the console:

Edit my-dropzone.js

// on success
myDropzone.on("successmultiple", function(file, response) {
    // get response from successful ajax request
    console.log(response);
    // submit the form after images upload
    // (if u want yo submit rest of the inputs in the form)
    // COMMENT THIS LINE TO PREVENT FORM SUBMIT
    // document.getElementById("dropzone-form").submit(); 
});

In uplaod.php

if ($_POST["dropzone"]) {
    /**
     *	Response 
     *	return json response to the dropzone
     *	@var data array
     */
    $data = [
        "files" => $_FILES,
    	"post" => $_POST,
    ];
    header('Content-type: application/json');
    echo json_encode($data);
    exit();
}

Open console in browser and you should see your $_POST and $_FILES data log.

Note that you can also send all form data along with the file, and then process whole form with ajax request, no form submission required:

// Add more data to send along with the file as POST data. (optional)
myDropzone.on("sending", function(file, xhr, formData) {
    formData.append("dropzone", "1"); // $_POST["dropzone"]
    emailValue = document.querySelector("input[name=email]").value;
    formData.append("email", emailValue ); // $_POST["email"]
    firstNameValue = document.querySelector("input[name=first_name]").value;
    formData.append("first_name", firstNameValue ); // $_POST["first_name"]
});

Then in your php do wht ever u want with your fields:

if ($_POST["dropzone"]) {
     
    $email = $_POST["email"];
    $first_name = $_POST["first_name"];

    // upload files
    // send emails

    /**
     *	Response 
     *	return json response to the dropzone
     *	@var data array
     */
    $data = [
    	status: "success"
        message: "Done!"
    ];
    header('Content-type: application/json');
    echo json_encode($data);
    exit();
}

@PkLearning
Copy link

thank you @kreativan it's useful!
now i try to get a name of file upload
can i get the name file passing $_POST?
when i print_r($_POST); it show only value in form

No, you cant access file related data after form submit. In this case print_r($_POST); gives u only rest of the form fields, but not the file, because file is sent and processed with ajax request.
But you can have access and preview $_POST data as a callback response from php (see uplaod.php).
In this case form is submitted right after file upload, and page is reloaded, so you miss the ajax response from php.

U can disable form submit after upload, so you can preview and test $_POST data as response in the console:

Edit my-dropzone.js

// on success
myDropzone.on("successmultiple", function(file, response) {
    // get response from successful ajax request
    console.log(response);
    // submit the form after images upload
    // (if u want yo submit rest of the inputs in the form)
    // COMMENT THIS LINE TO PREVENT FORM SUBMIT
    // document.getElementById("dropzone-form").submit(); 
});

In uplaod.php

if ($_POST["dropzone"]) {
    /**
     *	Response 
     *	return json response to the dropzone
     *	@var data array
     */
    $data = [
    	"post" => $_POST,
    ];
    header('Content-type: application/json');
    echo json_encode($data);
    exit();
}

Open console in browser and you should see your $_POST data log.

Note that you can also send all form data along with the file, and then process whole form with ajax request, no form submission required:

// Add more data to send along with the file as POST data. (optional)
myDropzone.on("sending", function(file, xhr, formData) {
    formData.append("dropzone", "1"); // $_POST["dropzone"]
    emailValue = document.querySelector("input[name=email]").value;
    formData.append("email", emailValue ); // $_POST["email"]
    firstNameValue = document.querySelector("input[name=first_name]").value;
    formData.append("first_name", firstNameValue ); // $_POST["first_name"]
});

Then in your php do wht ever u want with your fields:

if ($_POST["dropzone"]) {
     
    $email = $_POST["email"];
    $first_name = $_POST["first_name"];

    // upload files
    // send emails

    /**
     *	Response 
     *	return json response to the dropzone
     *	@var data array
     */
    $data = [
    	status: "success"
        message: "Done!"
    ];
    header('Content-type: application/json');
    echo json_encode($data);
    exit();
}

Finally, I finish upload file and insert to DB
I appreciate your help
Thank you very much

@sknair123
Copy link

Hello,

I need only execute the dropzone code once the form is valid. I use jQuery validation library for validating the form input fields.

`$('document').ready(function() {
$("#notification-property").hide();

/* handling form validation */
$("#property-form").validate({
rules: {
prop_title: "required",
prop_price: {
required: true,
digits: true
},
prop_area: {
required: true,
digits: true
},
prop_address: "required",
prop_message: {
required: true,
minlength: 10,
maxlength: 2000
},
prop_owner_name: "required",
prop_owner_email: {
required: true,
email: true
},
prop_owner_phone: {
required: true,
digits: true
},
},
messages: {
'prop_title': {
required: "Please enter title for your property"
},
prop_price: {
required: "Please enter price of your property",
digits: "Please enter price in digits (AED)"
},
prop_area: "Please enter Sqft of your property",
prop_address: "Please enter address of your property",
prop_message: {
required: "Please enter detailed Information",
minlength: "Please enter something about your property in 50 - 20000 characters",
maxlength: "Please enter something about your property in 50 - 20000 characters"
},

		prop_owner_name: "Please enter your name",
		prop_owner_email: {
			required: "Please enter your email address",
			email: "Please enter valid email address"

		},
		prop_owner_phone: {
			required: "Please enter your phone number",
			digits: "Please enter valid phone number"

		},
},
submitHandler: submitPropertyForm

});

/* Handling login functionality */
function submitPropertyForm() {
var data = $("#property-form").serialize();
$.ajax({
type: 'POST',
url: 'submit_property_data.php',
data: data,
beforeSend: function() {
$("#submit-button").html('   Submiting ...');
},
success: function(response) {
if (response == "ok") {
console.log(1);
document.getElementById("property-form").reset();
$("#notification-property").html(' ' + response + ' !').show();
//setTimeout(' window.location.href = "dashboard.php"; ',4000);
} else {
$("#notification-property").fadeIn(1000, function() {
$("#notification-property").html('' + response + ' !').fadeOut();
$("#submit-button").html('  Send');
});
}
},
complete:function(){
$('body, html').animate({scrollTop:$('form').offset().top}, 'slow');
}
});
return false;
}

$("#submit-button").bind('click', function() {
  if ( $("#property-form").valid() ) {
	  submitPropertyForm();
  } else {
	  console.log('form invalid');
  }

})

	Dropzone.autoDiscover = false;
	$(function () {
			$("div#myDropzone").dropzone({

					url: 'submit_property_data.php',
					addRemoveLinks: true,
					paramName: "file",
					maxFiles:11,
					uploadMultiple: true,
					autoProcessQueue: false,
					parallelUploads: 10,

					init: function () {

							var myDropzone = this;

							// Update selector to match your button
							$("#submit-button").click(function (e) {
									e.preventDefault();
									myDropzone.processQueue();
							});


							this.on('sending', function(file, xhr, formData) {
									// Append all form inputs to the formData Dropzone will POST
									var data = $('#property-form').serializeArray();
									$.each(data, function(key, el) {
											formData.append(el.name, el.value);
									});
							});

								this.on("success", function(file, responseText) {
										alert(responseText);
								});

						},


			});
	});

});
`

@kreativan
Copy link
Author

You can validate form inside dropzone init function before processing queue:


// Update selector to match your button
$("#submit-button").click(function (e) {
      e.preventDefault();
       if ( $("#property-form").valid() ) {
             myDropzone.processQueue();
      }
});

@sknair123
Copy link

@kreativan

Can you check your mailbox ?

@wnedoe
Copy link

wnedoe commented Jan 16, 2021

palceholder 2x should be placeholder ;-)

I was looking 10 minutes for it before i saw the typo :-P

@kreativan
Copy link
Author

@wnedoe thanks, I make these typos so often :)

@henockbarakael
Copy link

Hello @kreativan,
Please can you help me? I want to insert data from my form into DB using your dropzone code.

@henockbarakael
Copy link

This is my index.php

                                            <!-- start text deadline -->
                                            
                                            <div class="row">
                                                <div class="col-md-4 unit">
                                                    <div class="input">
                                                        <label class="icon-left" for="text">
                                                            <i class="fa fa-user"></i>
                                                        </label>
                                                        <input class="form-control" autocorrect="off" spellcheck="false" autocomplete="off" readonly onfocus="this.removeAttribute('readonly');" name="titre" type="text" placeholder="Titre"  id="text">
                                                    </div>
                                                </div>
                                                <div class="col-md-4 unit">
                                                    <div class="input select">
                                                        <select class="form-control" name="categorie">
                                                            <option value="none">Seléctionner une catégorie</option>
                                                            <option value="Homme">Homme</option>
                                                            <option value="Femme">Femme</option>
                                                        </select>
                                                        <i></i>
                                                    </div>
                                                </div>
                                                <div class="col-md-4 unit">
                                                    <div class="input select">
                                                        <select class="form-control" name="deadline">
                                                            <option value="none">Diffusion de votre annonce</option>
                                                            <option value="one_mounth">Pendant 1 mois</option>
                                                            <option value="two_mounth">Pendant 2 mois</option>
                                                            <option value="three_mounth">Pendant 3 mois</option>
                                                        </select>
                                                        <i></i>
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="row">
                                                <div class="col-md-4 unit">
                                                    <div class="input select">
                                                        <select class="form-control" name="status">
                                                            <option value="none">Vous êtes un?</option>
                                                            <option value="none">Particulier</option>
                                                            <option value="none">Professionnel</option>
                                                        </select>
                                                        <i></i>
                                                    </div>
                                                </div>
                                                <div class="col-md-4 unit">
                                                    <div class="input-group">
                                                        <span class="input-group-addon">$</span>
                                                        
                                                        <input class="form-control" autocorrect="off" spellcheck="false" autocomplete="off" readonly onfocus="this.removeAttribute('readonly');" name="montant" type="text" placeholder="30.000Fc">
                                                    </div>
                                                </div>
                                                <div class="col-md-4 unit">
                                                    <div class="input select">
                                                        <select class="form-control" name="type_annonce">
                                                            <option value="none">Type d'annonce</option>
                                                            <option value="none">Je propose</option>
                                                            <option value="none">Je recherche</option>
                                                        </select>
                                                        <i></i>
                                                    </div>
                                                </div>
                                            </div>
                                            <!-- end text deadline -->
                                            <div class="row">
                                                <div class="col-md-4 unit">
                                                    <div class="input">
                                                        <label class="icon-left" for="text">
                                                            <i class="fa fa-user"></i>
                                                        </label>
                                                        <input class="form-control" autocorrect="off" spellcheck="false" autocomplete="off" readonly onfocus="this.removeAttribute('readonly');" name="prenom" type="text" placeholder="Prénom"  id="text">
                                                    </div>
                                                </div>
                                                <div class="col-md-4 unit">
                                                    <div class="input">
                                                        <label class="icon-left" for="text">
                                                            <i class="fa fa-user"></i>
                                                        </label>
                                                        <input class="form-control" autocorrect="off" spellcheck="false" autocomplete="off" readonly onfocus="this.removeAttribute('readonly');" name="nom" type="text" placeholder="Nom"  id="text">
                                                    </div>
                                                </div>
                                                <div class="col-md-4 unit">
                                                    <div class="input">
                                                        <label class="icon-left" for="text">
                                                            <i class="fa fa-user"></i>
                                                        </label>
                                                        <input class="form-control" autocorrect="off" spellcheck="false" autocomplete="off" readonly onfocus="this.removeAttribute('readonly');" name="phone" type="text" placeholder="Téléphone"  id="text">
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="row">
                                                
                                                <div class="col-md-12 unit">
                                                    <div class="input">
                                                        <label class="icon-left" for="txt-icon-left">
                                                            <i class="fa fa-file-text-o"></i>
                                                        </label>
                                                        <textarea class="form-control" name="description" id="txt-icon-left" placeholder="Décrivez précisément votre bien, en indiquant son état, ses caractéristiques, ainsi que toute autre information importante pour l’acquéreur."></textarea>
                                                    </div>
                                                </div>
                                            </div>
                                            <!-- Dropzone -->
                                            <div class="card">
                                            <!-- Card header -->
                                            <div class="card-header">
                                                <h3 class="mb-0">Dropzone</h3>
                                            </div>
                                            <!-- Card body -->
                                            <div class="card-body">
                                                <div id="dropzone" class="dropzone"></div>
                                            </div>
                                            </div>
                                            <div class="form-footer" style="margin-top: 20px">
                                                <!--<button type="submit" class="btn btn-success primary-btn processing">Processing...</button>-->
                                                <button type="reset" class="btn btn-danger secondary-btn">Réinitialiser</button>
                                                <button id="submit-dropzone" type="submit" name="submitDropzone" class="btn btn-info primary-btn">Soumettre</button>
                                            </div>
                                            </form>

@henockbarakael
Copy link

henockbarakael commented May 27, 2021

My upload.php

// define absolute folder path
$dest_folder = 'uploads/';

if (!empty($_FILES)) {

// if dest folder doesen't exists, create it
if(!file_exists($dest_folder) && !is_dir($dest_folder)) mkdir($dest_folder);

/**
 *	Single File 
 *	uploadMultiple = false
 *	@var $_FILES['file']['tmp_name'] string, file_name
 */
// $tempFile = $_FILES['file']['tmp_name'];        
// $targetFile =  $dest_folder . $_FILES['file']['name'];
// move_uploaded_file($tempFile,$targetFile); 

/**
 *  Multiple Files
 *  uploadMultiple = true
 *  @var $_FILES['file']['tmp_name'] array
 *
 */
foreach($_FILES['file']['tmp_name'] as $key => $value) {
    $tempFile = $_FILES['file']['tmp_name'][$key];
    $targetFile =  $dest_folder. $_FILES['file']['name'][$key];
    move_uploaded_file($tempFile,$targetFile);
}

/**
 *	Response 
 *	return json response to the dropzone
 *	@var data array
 */
if ($_POST["dropzone"]) {
 
    $host = "localhost";
    $root = "root";
    $pwd = "";

    try {
    $conn = new PDO("mysql:host=$host;dbname=ecomm", $root, $pwd);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
    }
    $titre = $_POST["titre"];
    $categorie = $_POST["categorie"];
    $deadline = $_POST["deadline"];
    $status = $_POST["status"];
    $montant = $_POST["montant"];
    $type_annonce = $_POST["type_annonce"];
    $prenom = $_POST["prenom"];
    $nom = $_POST["nom"];
    $phone = $_POST["phone"];
    $description = $_POST["description"];
    $stmt = $conn->prepare("insert into annonce set titre=?, categorie=?, deadline=?, status=?,montant=?, type_annonce=?, prenom=?, nom=?, phone=?, description=?, photos=?");
    $stmt->execute([$titre, $categorie, $deadline, $status, $montant, $type_annonce, $prenom, $nom, $phone, $description, $targetFile]);


    // upload files
    // send emails

    /**
     *	Response 
     *	return json response to the dropzone
     *	@var data array
     */
    $data = [
        status: "success"
        message: "Done!"
    ];
    header('Content-type: application/json');
    echo json_encode($data);
    exit();
}

}

@kreativan
Copy link
Author

Hi,
You can upload files and handle db stuff in one ajax request.

if ($_POST["dropzone"]) {
    
    // Uplod file
    // need to define destination $dest_folder = ""
    $tempFile = $_FILES['file']['tmp_name'];        
    $targetFile =  $dest_folder . $_FILES['file']['name'];
    move_uploaded_file($tempFile,$targetFile); 
    
    // do your db stuff
    // save file path to the db, in this case that's $targetFile
    .... connect to db...
    $image= $targetFile;
   
   $response = [
       status => "success"
   ]
   
    header('Content-type: application/json');
    echo json_encode($response);
    exit();
}

@HermanMonteiro
Copy link

HermanMonteiro commented Aug 12, 2021

Hello how are you?
I need to validate if there is any file in POST. What is the way to do this using dropzone?

I tried it this way but it didn't work. I want to check if there is at least 3 files in the form, if it doesn't exist then it displays a message and doesn't trigger the form.

init: function () {
            var myDropzone = this;
            $('html').on('submit', '.sendMail_form', function (e) {
                e.preventDefault();
                var form = $(this);
                form.find('img').fadeIn('fast').css('display', 'inline-block');
                if (myDropzone.files !== "") {
                    myDropzone.processQueue();
                } else {     
                    $('.sendMail_form').find('img').fadeOut('slow', function () {
                        swal.fire({
                            "title": 'ATTENTION',
                            "text": 'It is mandatory to attach all documentation, check at the end of this page if any documents are missing.',
                            "type": 'warning',
                            "confirmButtonClass": 'btn btn-warning',
                        });
                    });
                }
            });

@kreativan
Copy link
Author

Hi,
Try to use myDropzone.files.length > 0 instead of myDropzone.files !== "" to check if there is files attached

@erickjones
Copy link

My friend, thank you. The only way I could make it work was with your code.
How would you display the files already uploaded to the server?
I am using dropzone to upload a form with images and other inputs. Now I want to give the user the possibility to edit the entry. So I want to retrieve what the user did and display in the form having it already filled.

@anthing1466
Copy link

Hello Kreativan,
Is it to be used as plugin for WP for example ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment