从文件系统拖放到Web应用程序中

时间:2010-03-05 15:51:15

标签: web-applications file-upload drag-and-drop

我正在调查一个web框架/技术,它允许将n个文件系统中的文件拖放到Web应用程序中。当然,目的是将这些文件上传到应用程序服务器。

在Flex中似乎不可能(尽管它适用于AIR)。 我找到了使用Google Gears的方法,但这迫使用户将Gears安装为浏览器插件。

使用Java applet,它似乎是可能的,但它需要用户接受安全规则异常...(对我来说很奇怪,因为通过DnD读取用户指定的文件并不比“安全”更“安全”。如果用户通过标准的经典上传对话框指定了文件......)。

是否有任何非侵入性方式允许此功能,无需安装任何插件且不接受安全警告消息框?

3 个答案:

答案 0 :(得分:4)

没有

浏览器通常不支持内置的此类内容。

答案 1 :(得分:4)

Firefox 3.6显然是最新的Safari(也许是Webkit nightly)通过HTML5支持这一点。我最近一直在玩它并且效果很好。我做的示例只是在页面中插入缩略图,但可以调整以将数据上传到服务器。这是我写的JavaScript / jquery代码,随意使用它:

function debug(string) {
  $("#debugArea").append(string);
}

$(function() {
  // We need to override the dragover event, otherwise Firefox will just open the file on drop
  $("#dropArea").bind("dragover", function(event) {
    event.preventDefault();
  });

  // This is where the actual magic happens :)
  $("#dropArea").bind("drop", function(event) {
    event.preventDefault();
    debug("Dropped something: ");
    // Since jquery returns its own event object, we need to get the original one in order to access the files
    var files = event.originalEvent.dataTransfer.files;
    // jquery nicely loops for us over the files
    $(files).each(function(index, file) {
     if(!file.type.match(/image.*/)) { // Skip non-images
        debug(file.name)
        debug(" <em>not an image, skipping</em>; ");
        return;
      }

      // We need a new filereader for every file, otherwise the reading might be canceled by the next file
      var filereader = new FileReader();
      filereader.onloadend = function(event) { $("#thumbnails").append("<img src='"+event.target.result+"' width='100px' />"); };
      debug(file.name);
      debug("; ");

      // Read the file in data URL format so that we can easily add it to an img tag.
      filereader.readAsDataURL(file);
    });
    debug("<br/><br/>");
  })

});

以及它的HTML:

<div id="dropArea">
  <p>Drop images here!</p>
</div>
<div id="thumbnails">
</div>
<div id="debugArea">
  <strong>Debug Info:</strong><br/>
</div>

答案 2 :(得分:0)

现在可以通过使用HTML5 File API来实现。

甚至可以drag & drop folders