Friday, September 8, 2017

How to use Dropzone.js

1. Download dropzone.js from here: http://www.dropzonejs.com/
or here: https://github.com/enyo/dropzone

2. What we need is "dropzone.min.js" and "dropzone.min.css". Move them into your directory, for example, like this "(current directory)/script".


3. Download jQuery or simply use CDN:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Or specify where the jQuery file is downloaded:
<script src="./the/file/of/jQuery.js"></script>

4. Write as follows and save it as .html file.
<head>
    <link rel="stylesheet" type="text/css" href="./script/dropzone.min.css">
</head>
<form>
    <div id="dZUpload" class="dropzone">
        <div class="dz-default dz-message"></div>
    </div>
</form>
<!-- Use CDN of jQuery of google -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="./script/dropzone.min.js"></script>
<script>
    Dropzone.autoDiscover = false;
    $(document).ready(function () {
        $("#dZUpload").dropzone({
            url: "http://192.168.1.1/upload.php", //Your target URL
            addRemoveLinks: true,
            //If you use cakaphp 3, we need to write about csrf information.
            /*headers: {
                'X-CSRFToken': $('meta[name="token"]').attr('content')
            },*/
            success: function (file, response) {
                var imgName = response;
                //For the animation of success.
                file.previewElement.classList.add("dz-success");
                //To add id to the previews.
                //file.previewElement.id = response.id;
                console.log("Successfully uploaded :" + imgName);
            }
        });
    });
</script>

5. Open the .html file from a browser. We will see we can use the dropzone.
image cited from: https://www.npmjs.com/package/dropzone

But if the provided URL is not valid, you will see that error symbols appear on the previews:
In that case, Press F12 on the browser and check the errors:

If you are using PHP for the sever side, use "echo" in php function to send data back to dropzone.js as the "response" variable in the success-event function. Also use json_encode in the php function to send an object as it is to javascript.