Using Dropzone.js with PHP and Ajax request

I have been working on a web app recently and it used FileReader to upload files and needed some functionality to limit upload file size and do some compression or resizing to stop users uploaded ridiculously large photo images. So after not having great luck with the resizing I decided to investigate Dropzone.js which takes care of all my problems. It is easy to set up a demo program but was a two week effort to make it usable with an app that has additional fields to upload and to use an Upload button.

Hence the following program that I will not comment on except to say: if you need a submit button, do not use type=submit but rather use a button to stop the action and check for a form submit function rather than a submit button to get the action going. And #2, be sure the form has a form action set with the url you wish to go to or else it just won’t happen. Delete the xmp tags.

 <xmp>

<div class="container" >
  <div class="row">
    <div class="col-md-12">
<body>
      <h2>PHP Dropzone File Upload on Button Click Example</h2>
      <form action="ajax.php?action=save_upload"  method="post" class="dropzone" id="form_upload" name="form_upload" enctype="multipart/form-data">

        <div>
          <h3>Upload Multiple Image By Click On Box</h3>
<textarea name="content" id="" cols="30" rows="4" placeholder="Write a content for your post here" class="form-control"></textarea>
        <input name="file" type="hidden" name="file" />
<button class="btn btn-sm btn-primary btn-block col-md-2  offset-md-10"><i class="fa fa-upload"></i> Upload</button>
        </div>
      </form>
</body>      
    </div>
  </div>
</div>

<script type="text/javascript">
    Dropzone.autoDiscover = false;
  
    var myDropzone = new Dropzone(".dropzone", { 
       autoProcessQueue: false,
       acceptedFiles : "image/*",
       addRemoveLinks: true,
       maxFilesize: 1,
       acceptedFiles: ".jpeg,.jpg,.png,.gif",
       resizeWidth: 500, resizeHeight: 1000,
       resizeMethod: 'contain', resizeQuality: 1.0,
       paramName: "file",
init: function () {

        var myDropzone = this;

        // Update selector to match your button
        $("#button").click(function (e) {
            e.preventDefault();
            myDropzone.processQueue();
console.log("Files qued");

        });


}
       
      
   
    });
  

</script>

<script type="text/javascript">
$(document).ready(function() {
console.log("doc ready");
    $("#form_upload").submit(function(e){ 
      e.preventDefault();
      e.stopPropagation();
      myDropzone.processQueue();
//Dropzone.forElement(".dropzone").processQueue(); 
 //     var str = $(this).serialize();
console.log("calling ajax");
        $.ajax({
                type: "POST",
                url:'ajax.php?action=save_upload',
        //        url: "test_print.php",
                data:  new FormData(this),
 //data: {test:'test'},
                dataType:'json',
               // contentType: "application/x-www-form-urlencoded",
                contentType: false,
                processData: false,
                dataType: 'text',
                success: function(response){
                    alert(response);
                    console.log(response);
                    //echo what the server sent back...
                }
            });
        return(false);
    });
});
</script>

 









	

  
// PHP code: 
<?php
//print_r($_FILES);

$folder_name = 'assets/img/uploads/';

if(!empty($_FILES))
{
 $temp_file = $_FILES['file']['tmp_name'];
echo($temp_file);
 $location = $folder_name . $_FILES['file']['name'];
 move_uploaded_file($temp_file, $location);
}



</xmp>

About Jim Demello

Christian, ESL teacher, retired computer programmer, former US Army soldier, former Peace Corps Volunteer. Like to paint acrylic portraits, build and fly rc airplanes, play guitar and ukulele, juggle, and hang out with my Chinese wife. Am currently residing in a foreign country but I do love America.
This entry was posted in Uncategorized and tagged , . Bookmark the permalink.

Leave a comment