kreativan
3/28/2019 - 10:56 AM

Dropzone.js php

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();

}