Trình xử lý sự kiện nào là cần thiết?
Drag'n'drop yêu cầu trình duyệt HTML5 - nhưng đó là tất cả chúng hiện nay.
Tôi khuyên bạn không nên bắt đầu từ đầu vì có khá nhiều mã cần thiết - Tôi khá thích trình bao bọc này triển khai thực hiện như một plugin jQuery.
http://www.github.com/weixiyen/jquery-filedrop
Sau khi xác định một phần tử trong tài liệu với lớp div, bạn có thể khởi nó để chấp nhận các file giảm với:
function fileSetUploadPercent(percent, divID){
var uploadString = "Uploaded " + percent + " %";
$('#'.divID).text(uploadString);
}
function fileUploadStarted(index, file, files_count){
var divID = getDivID(index, file);
createFileUploadDiv(divID); //create the div that will hold the upload status
fileSetUploadPercent(0, divID); //set the upload status to be 0
}
function fileUploadUpdate(index, file, currentProgress){
//Logger.log("fileUploadUpdate(index, file, currentProgress)");
var string = "index = " + index + " Uploading file " + file.fileName + " size is " + file.fileSize + " Progress = " + currentProgress;
$('#status').text(string);
var divID = getDivID(index, file);
fileSetUploadPercent(currentProgress, divID);
}
function fileUploadFinished(index, file, json, timeDiff){
var divID = getDivID(index, file);
fileSetUploadPercent(100, divID);
if(json.status == "OK"){
createThumbnailDiv(index, file, json.url, json.thumbnailURL);
}
}
function fileDocOver(event){
$('#fileDropTarget').css('border', '2px dashed #000000').text("Drop files here");
}
$(".fileDrop").filedrop({
fallback_id: 'fallbackFileDrop',
url: '/api/upload.php',
// refresh: 1000,
paramname: 'fileUpload',
// maxfiles: 25, // Ignored if queuefiles is set > 0
maxfilesize: 4, // MB file size limit
// queuefiles: 0, // Max files before queueing (for large volume uploads)
// queuewait: 200, // Queue wait time if full
// data: {},
// headers: {},
// drop: empty,
// dragEnter: empty,
// dragOver: empty,
// dragLeave: empty,
// docEnter: empty,
docOver: fileDocOver,
// docLeave: fileDocLeave,
// beforeEach: empty,
// afterAll: empty,
// rename: empty,
// error: function(err, file, i) {
// alert(err);
// },
uploadStarted: fileUploadStarted,
uploadFinished: fileUploadFinished,
progressUpdated: fileUploadUpdate,
// speedUpdated
});
Các bit của trang web mà chấp nhận cập nhật có HTML này.
<div class='fileDrop'>
Upload a file by dragging it.
<span id='fileDropTarget'/>
</div>
File thả hoạt động trên ngoài <div> nhưng nó đẹp để thực hiện một mục tiêu lớn thoải mái nói rằng 'thả ở đây' để người dùng không nhầm lẫn về nơi họ cần phải thả các tập tin.
Hãy xem plugin này (không sử dụng, nhưng hãy xem mã nguồn). Họ thực hiện một tính năng kéo và thả tương tự như những gì bạn muốn. https://github.com/blueimp/jQuery-File-Upload – swatkins
Cụ thể hãy xem tệp này và phương thức onDrop: https://github.com/blueimp/jQuery-File-Upload/blob/master/js/ jquery.fileupload.js – swatkins