刚做完这个功能,把关键代码拿出来分享一下,如有毛病,各位指正。
//进入
jsDrag.addEventListener( "dragenter", function (e) {
e.preventDefault();
dragTip.text( "drop it" );
}, false);
//拖动
jsDrag.addEventListener( "dragover", function (e) {
e.preventDefault();
}, false );
//离开
jsDrag.addEventListener( "dragleave", function (e) {
e.preventDefault();
}, false );
//松开
特别注意一个万年坑: 绑定事件时用原生js对象,否则drop的时候获取不到dataTransfer属性。
jsDrag.addEventListener( "drop", function (e) {
e.preventDefault();
dragTip.text( "Or simply drag files to here" );
var dt = e.dataTransfer;
uploadFile( dt.files[0] );
}, false );
//文件上传
function uploadFile( fObj ){
var fSize = ( fObj.size / 1024 / 1024 ).toFixed(2),
fName = fObj.name,
fType = fObj.type;
var fd = new FormData();
fd.append( "uploadfile", fObj );
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener( "load", uploadComplete, false );
xhr.addEventListener( "error", uploadFailed, false );
xhr.addEventListener( "abort", uploadCanceled, false );
xhr.open( "POST", url, true );
xhr.send( fd );
}
//进度把控
function uploadProgress( evt ){
if( evt.lengthComputable ){
var percentComplete = Math.round( evt.loaded * 100 / evt.total );
console.log( "已上传:" + percentComplete );
}
}
(完)
最全的前端资源导航:http://www.iwan0.com/
里面还有时常更新的冷笑话哟