2011-07-07 72 views
9

我試圖找到一種讓用戶將單個文件拖放到頁面上的某個區域,然後可以將其與所有其他表單數據一起提交的方法。jquery中的文件拖放事件

在我的研究中,我發現了多個「拖放」上傳腳本,但他們都做到了,太多了。我想自己處理實際上傳的內容,並提供一種方法讓用戶上傳文件,而不會觸擊瀏覽按鈕。

在jquery(或類似的)中是否存在我應該查找的事件?

任何幫助非常感謝!

+0

一個完整的庫是jQuery文件上傳(http://blueimp.github.com/jQuery-File-Upload/)。OSS和MIT許可。 – koppor

回答

6

Plupload是一個jQuery插件來做多文件上傳,並從桌面支持HTML 5拖放。它很容易配置,檢查http://www.plupload.com/example_queuewidget.php

如果你不想上傳功能,請查看以下內容:

拖放從桌面和存儲到本地存儲http://jsdo.it/hirose31/7vBK

jQuery的FileDrop - HTML5可拖放文件https://github.com/weixiyen/jquery-filedrop

HTML5http://www.html5rocks.com/en/features/filehttp://xquerywebappdev.wordpress.com/2010/05/21/drag-n-drop-from-desktop-jquery-plugin/

19

我碰到這個問題就來了,同時研究一些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); 
+1

我發現只聽「drop」不會在Chrome中捕捉文件,它只在聽到給定元素上的「dragover」和「drop」時停止,並且在.stopPropagation()&.preventDefault()這兩個事件 –