I am investigating on a web framework/techno that allows to drag n drop files from the filesystem into a web application. The purpose is of course to upload those files into an application server.
In Flex it seems to be not possible (although it works with AIR). I have found a way with Google Gears, but this force the user to install Gears as a browser plugin.
With an Java applet, it seems to be possible but it requires the user to accept a security rule exception... (it is strange for me since reading a file specified by the user via DnD is not "less secure" than if the user had specified the file via standard classical Upload dialog box...).
Is there any non intru开发者_开发问答sive way to allow this feature, without installing any plugin and without accepting a security warning message box?
No.
Browsers don't generally have support for this sort of thing built in.
Firefox 3.6 and apparently the latest Safari (maybe Webkit nightly) support this through HTML5. I've been playing around with it recently and it works pretty well. The example I made just inserts thumbnails into the page, but this could be adjusted to upload the data to a server. Here is the JavaScript/jquery code I wrote, feel free to use this:
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/>");
})
});
And the HTML for it:
<div id="dropArea">
<p>Drop images here!</p>
</div>
<div id="thumbnails">
</div>
<div id="debugArea">
<strong>Debug Info:</strong><br/>
</div>
This is now possible through the use of the HTML5 File API.
- Many turnkey solutions/examples :
- http://www.freshdesignweb.com/jquery-html5-file-upload.html
- A library for doing so quick & easy:
- https://code.google.com/p/html5uploader/
- A more technical tutorial is available here:
- http://www.sitepoint.com/html5-file-drag-and-drop/ (demo)
It is even possible to drag & drop folders.
精彩评论