gpt4 book ai didi

javascript - jquery中的文件拖放事件

转载 作者:可可西里 更新时间:2023-11-01 02:52:32 27 4
gpt4 key购买 nike

我正在尝试找到一种方法,让用户可以将单个文件拖放到我页面上的某个区域,然后可以将这些文件与我的所有其他表单数据一起提交。

在我的研究中,我发现了多个“拖放”上传脚本,但它们都做得太多了。我想自己处理实际的上传,只是为用户提供一种无需点击浏览 按钮即可上传文件的方式。

我应该寻找 jquery(或类似的东西)中的事件吗?

非常感谢任何帮助!

最佳答案

我在研究一些 AJAX 文件上传技术时遇到了这个问题。

我今天创建了一个拖放上传脚本(它仍处于概念验证阶段,但这是我采取的基本步骤。

$('drag-target-selector').on('drop', function(event) {

//stop the browser from opening the file
event.preventDefault();

//Now we need to get the files that were dropped
//The normal method would be to use event.dataTransfer.files
//but as jquery creates its own event object you ave to access
//the browser even through originalEvent. which looks like this
var files = event.originalEvent.dataTransfer.files;

//Use FormData to send the files
var formData = new FormData();

//append the files to the formData object
//if you are using multiple attribute you would loop through
//but for this example i will skip that
formData.append('files', files[0]);

}

现在您可以发送 formData 以供 php 脚本或您要使用的任何其他内容处理。我没有在我的脚本中使用 jquery,因为它有很多问题,使用常规 xhr 似乎更容易。这是代码

var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php');
xhr.onload = function() {
console.log(xhr.responseText);

};


xhr.upload.onprogress = function(event) {
if (event.lengthComputable) {
var complete = (event.loaded / event.total * 100 | 0);
//updates a <progress> tag to show upload progress
$('progress').val(complete);

}
};

xhr.send(formData);

关于javascript - jquery中的文件拖放事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6604622/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com