只是在这里叮叮当当,因为我一直在做这个以及最近几天。根据我的理解,如果你通过jQuery绑定drop事件,你需要通过在jQuery提供的事件中通过event.originalEvent
对象来访问event.dataTransfer
对象。
实施例:
在此我结合到两个dragover
以及drop
事件,这是必要的,以防止它在执行默认动作(发现溶液这里:Prevent the default action. Working only in chrome)
$('#dropzone').bind('dragover drop', function(event) {
event.stopPropagation();
event.preventDefault();
if (event.type == 'drop') {
console.log(event.originalEvent.dataTransfer.files);
}
});
也有似乎有一个错误,如果你console.log()
event.dataTransfer
(或event.originalEvent.dataTransfer
)它的文件数组是空的,这里指出:event.dataTransfer.files is empty when ondrop is fired?
为了更好地回答了OP的问题(我只注意到它的其余部分,我知道这是旧的,但有人可能会有所帮助):
我的实现是在jQuery的,所以我希望这是正常的:
var files = [];
// Attaches to the dropzone to pickup the files dropped on it. In mine this is a div.
$("#dropzone").bind('dragover drop', function(event) {
// Stop default actions - if you don't it will open the files in the browser
event.stopPropagation();
event.preventDefault();
if (e.type == 'drop') {
files.push(event.originalEvent.dataTransfer.files);
}
});
// Attach this to a an input type file so it can grab files selected by the input
$("#file-input").bind('change', function(event) {
files.push(event.target.files);
});
// This is a link or button which when clicked will do the ajax request
// and upload the files
$("#upload-button").bind('click', function(event) {
// Stop the default actions
event.stopPropagation();
event.preventDefault();
if (files.length == 0) {
// Handle what you want to happen if no files were in the "queue" on clicking upload
return;
}
var formData = new FormData();
$.each(files, function(key, value) {
formData.append(key, value);
});
$.ajax({
url: 'upload-ajax',
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
processData: false, // Don't process the files - I actually got this and the next from an SO post but I don't remember where
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR) { /* Handle success */ },
error: function(jqXHR, textStatus, errorThrown) { /* Handle error */ }
});
});
你也可以绑定到被接受的答案中的其他事件,例如使dropzone淡入,以便你可以看到它(这是我的图书馆的待办事项列表)。但是,这是我使用的实际ajax文件上传的核心。
我真的没有一个方便的方法来测试它,但实质上我是这么做的(我基本上从我制作的库中取出所有代码并将其调整为适合一般代码块在这里以一种容易理解的方式)。希望这可以帮助一些人。从这里开始,实际上很容易,可以添加文件队列列表,并且可以从队列中删除文件,所以这应该是一个很好的起点。
我认为只有支持HTML5的浏览器才能让你做到这一点。但我不是100%确定的。 – JesseBuesking
你可以使用原生javascript做一些非常酷的事情,例如拖动一个托管的图像(从一个网站),并把它放在一个有drop事件的div上,然后获取图像的路径并创建作为源代码的具有该路径的图像元素。但是,从桌面拖动图像完全是另一回事,并且很可能会被阻止。 –