How do I preload images into dropzone.js

末鹿安然 提交于 2019-11-29 20:26:59

Proper way to do it is to use .emit method provided by on dropzone js to add a file and thumbnail to preload images from the server. See sample code below. Taken from https://github.com/enyo/dropzone/wiki/FAQ#how-to-show-files-already-stored-on-server

// Create the mock file:
var mockFile = { name: "Filename", size: 12345 };

// Call the default addedfile event handler
myDropzone.emit("addedfile", mockFile);

// And optionally show the thumbnail of the file:
myDropzone.emit("thumbnail", mockFile, "/image/url");

.emit method from dropzone will trigger init function and if you have any addedfile event callback written for it. e.g. I am using addedfile event add remove button and also attached delete image functionality.

Dropzone is so strong and awesome that you can do anything on it .
Steps to Follow -- >

1)First of all you will have to create a server side script which will get all the filenames and its size and send it as json response.
PHP code :

  foreach($myitemfiles as $file){ //get an array which has the names of all the files and loop through it 
        $obj['name'] = $file; //get the filename in array
        $obj['size'] = filesize("uploadsfolder/".$file); //get the flesize in array
        $result[] = $obj; // copy it to another array
      }
       header('Content-Type: application/json');
       echo json_encode($result); // now you have a json response which you can use in client side 

2)Now you can use the response to display the uploaded files.Write the below code inside the dropzone init function
Javascript Code :

  init: function() {

      var thisDropzone = this;

        $.getJSON('get_item_images.php', function(data) { // get the json response

            $.each(data, function(key,value){ //loop through it

                var mockFile = { name: value.name, size: value.size }; // here we get the file name and size as response 

                thisDropzone.options.addedfile.call(thisDropzone, mockFile);

                thisDropzone.options.thumbnail.call(thisDropzone, mockFile, "uploadsfolder/"+value.name);//uploadsfolder is the folder where you have all those uploaded files

            });

        });
}

Note : don't take the whole file url path in filename just take the filename itself thats it .
This works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!