2014-03-26 22 views
22

我有以下选项的网页上dropzone.js实例:我如何预先载入图像到dropzone.js

autoProcessQueue:false 
uploadMultiple:true 
parallelUploads:20 
maxFiles:20 

据编程实例化,因为它是一个大表单的一部分。当表单提交时,我已经装好了处理队列。

我的目标是让我的用户能够使用dropzone来管理项目的图像,因此当我加载项目的“编辑/更新”视图时,我想预先加载图像的拖放区域之前已经为该项目上传的内容。有没有一种很好的方法来实现这一点,以便已有的项目在将更改提交到图像列表时不会重新上传?

回答

27

正确的做法是使用dropzone js提供的.emit方法添加文件和缩略图,以便从服务器预加载图像。请参阅以下示例代码。从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方法取自悬浮窗会引发初始化函数,如果您有任何addedfile事件回调为其编写。例如我正在使用addfile事件添加删除按钮,并附加删除图像功能。

+1

如果您限制了可以上传的文件数量,则必须添加myDropzone.files。推(mockFile);继续执行此上传限制。 –

+0

真的,您应该始终包含来自Kent的行(myDropzone.files.push(mockFile)),否则调用myDropzone.removeAllFiles()将不会删除预先填充的文件。 – Justin

26

Dropzone是如此强大和令人敬畏,你可以做任何事情。
要遵循的步骤 - >

1)你必须创建一个服务器端脚本,这将 得到所有的文件名和它的大小并将其作为JSON响应的第一。
PHP代码:

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)现在你可以使用响应显示上传files.Write悬浮窗初始化函数里面下面的代码
JavaScript代码:

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 

      }); 

     }); 
} 

注意:不采取文件名中的整个文件的url路径只需要文件名本身就是它。
This works

+0

谢谢,这是有效的。但是,应该指出,直接调用附加文件和缩略图函数会绕过相应的事件,这对我的目的来说很好。 另一个怪癖:我必须在缩略图调用中生成服务器端的缩略图,因为使用该图像直接绕过dropzone的客户端缩略图生成,并且只是将全尺寸图像粘贴到预览元素中而不进行裁剪,所以矩形图像将被压扁。 – ralbatross

+2

当我使用此方法预加载图像时,图像中仍然存在进度条(使用默认css)。我如何删除此栏? –

+0

当添加这样的文件时,它并不遵循maxFiles。我有最大文件为1,当我尝试上传新文件时,它接受文件。 –