拖动文件和jQuery的拖放事件拖动、拖放、事件、文件

2023-09-10 16:49:33 作者:你逗她笑还陪她闹

我试图找到让的一种方式用户拖放单个文件转换成可以再随着我的所有其他形式的数据得到提交我的网页的区域。

I'm trying to find a way of letting users drag and drop individual files into an area on my page that can then get submitted along with all my other form data.

在我的研究,我发现多个拖放上传脚本,但他们都做的方式,方法太多了。我要处理的实际上传自己,只是提供一种方法让用户上传文件没有击中的浏览的按钮。

In my research I've found multiple "drag and drop" upload scripts but they all do way, way too much. I want to handle the actual uploading myself and just provide a way for users to upload files without hitting the browse button.

有jQuery中(或类似的东西)的事件,我应该找谁?

Is there an event in jquery (or something similar) that I should be looking for?

任何帮助是非常AP preciated!

Any help is much appreciated!

推荐答案

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

I came across this question while researching some AJAX file upload techniques.

我创建了一个阻力,今天(放弃其仍处于概念阶段的证明上传脚本,但继承人,我采取了基本的步骤。

I created a drag and drop upload script today (its still in proof of concept stage but heres the basic steps that I took.

$('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。下面是code

now you can send formData to be processed by a php script or whatever else you want to use. I didn't use jquery in my script as there a lot of issues with it it seemed easier to use regular xhr. Here is that code

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);