Gmail和QQ郵箱都實現(xiàn)了在Chrome下的拖拽上傳,于是我又查了一些資料終于也實現(xiàn)了Chrome下的拖拽上傳。沒有看Gmail和QQ郵箱寫信頁的源碼,但是在http://stackoverflow.com/questions/2657653/drag-and-drop-file-upload-in-google-chrome-chromium這里找到了一些解決的方案,因為Chrome不支持FileReader,所以無法通過模擬文件上傳的方式來用Ajax上傳,有些人給出了一些方法,比如可以通過將文件拖拽到一個<input type=”file” multiple />,并且將這個input的透明度設(shè)為0,Chrome支持將文件拖拽到input里面,所以可以觸發(fā)這個input的change事件,將它提交到一個iframe里面,QQ郵箱在Chrome下貌似是采用這種方式。在這個帖子的最后面有個人給出了一個DEMO,我認為是一個比較好的解決方案,因為Chrome支持FormData,F(xiàn)ormData為XMLHttpRequest 2提供了便捷的方法來構(gòu)造表單的鍵值對,只需要通過send方法就可以了。最后我的關(guān)鍵代碼是這樣的:
this.uploadDragFile = function(file, index){
var xhr = new XMLHttpRequest(), _this = this;
xhr.upload.addEventListener(”progress”, function(e){
if(e.lengthComputable){
var percentage = Math.round(e.loaded*100/e.total);
$(”att_prog_drag_”+index).style.width = percentage + “%”;
}
}, false);
xhr.addEventListener(”error”, function(e){
var pn = $(”att_prog_drag_”+index).parentNode;
pn.style.display = “none”;
var em = document.createElement(”em”);
em.style.color = “red”;
em.style.marginLeft = “6px”;
em.innerHTML = “上傳失敗”;
pn.parentNode.insertBefore(em, pn);
}, false);
xhr.addEventListener(”load”, function(e){
var pn = $(”att_prog_drag_”+index).parentNode;
pn.style.display = “none”;
try{
eval(”var data=”+xhr.responseText+”;”);
}catch(e){
var data = null;
}
var pn = $(”att_prog_drag_”+index).parentNode;
pn.style.display = “none”;
if(data && data.result){
_this._attList["file_drag_"+index] = data["data"];
_this.setAttach(_this._attList);
}else{
var em = document.createElement(”em”);
em.style.color = “red”;
em.style.marginLeft = “6px”;
em.innerHTML = data.msg || “上傳失敗”;
pn.parentNode.insertBefore(em, pn);
}
}, false);
xhr.open(”POST”, “/classic/uploadatt.php?email=”+runtime._conf["uid"]);
if (typeof(window.FormData) != “undefined”) {
var form = new FormData();
form.append(”Filedata”, file);
xhr.send(form);
}else{
var boundary = “xxxxxxxx”;
xhr.setRequestHeader(”Content-Type”, “multipart/form-data; charset=x-user-defined; boundary=”+boundary);//simulate a file MIME POST request;
xhr.setRequestHeader(”Content-Length”, file.size);
var body = “–” + boundary +”\r\n”;
body += “Content-Disposition: form-data; name=’Filedata’; filename=’” + encodeURIComponent(file.name) + “‘\r\n”;
body += “Content-Type: application/octet-stream\r\n\r\n”;
body += file.getAsBinary() + “\r\n”;
body += “–” + boundary + “–”;
xhr.sendAsBinary(body);
}
};