只是为了插话一下,因为过去几天我也一直在这样做。据我了解,如果您通过 jQuery 绑定 drop 事件,您需要访问该事件event.dataTransfer
对象通过经过event.originalEvent
jQuery 提供的事件中的对象。
Example:
在此我绑定到dragover
也drop
事件,因为这是防止它执行默认操作所必需的(在此处找到解决方案:防止默认操作。仅适用于镀铬 https://stackoverflow.com/questions/14282367/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()
the event.dataTransfer
(or event.originalEvent.dataTransfer
)它的文件数组为空,这里指出:ondrop 触发时 event.dataTransfer.files 为空? https://stackoverflow.com/questions/11573710/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 */ }
});
});
您还可以绑定到已接受答案中的其他事件来执行效果,例如使拖放区淡入,以便您可以看到它(这在我的图书馆的待办事项列表中)。然而,这是我实际使用的 ajax 文件上传的核心。
我确实没有一种方便的方法来测试它,但这本质上就是我的做法(我基本上从我一直在制作的库中获取了所有代码,并对其进行了调整,以一种简单的方式适应此处的通用代码块)理解方式)。希望这可以帮助一些人。从这里开始,实际上很容易继续添加文件队列列表,并且能够从队列中删除文件,所以这应该是一个非常好的起点。