1. 文件拖拽
不多说了,看代码和注释。貌似 Chrome 和 Firefix 都支持的。
var dragOver = function (event) { // 阻止默认事件 event.stopPropagation(); event.preventDefault();// 修改样式 this.className = "xx-over"; }; var dragLeave = function (event) { event.stopPropagation(); event.preventDefault(); this.className = "xx"; }; var drop = function (event) { event.stopPropagation(); event.preventDefault(); this.className = "xx"; var files = event.dataTransfer.files; for (var i = 0; i < files.length; i++) { // 可在此对文件进行大小和类型的限制 files[i].type files[i].size // 正式上传 uploadFile(files[i]); } }; // 把文件拖拽于 content 容器上,监听拖拽中、拖拽结束、拖拽离开的事件 var content = document.getElementById("XXX"); content.addEventListener("dragover", dragOver, false); content.addEventListener("dragleave", dragLeave, false); content.addEventListener("drop", drop, false);</pre>
2. 文件上传
基础知识准备
- XMLHttpRequest 请求
var request = new XMLHttpRequest(); request.open('GET', 'file:///home/user/file.json', false); request.send(null);
open 参数说明
@param {string} 请求方式: GET, POST, PUT, DELETE
@param {string} 请求地址。注:可以是本地文件哦。
@param {boolean} 同步: false; 异步: true
其余常用属性,在此就不解释,解释也只是翻译而已 ^^
request.onreadystatechange
request.readyState
request.responseText
request.statusText
request.statuse
- FormData Object
var formElement = document.getElementById("formId"); // 如果没有 form 元素,可以不用传入该参数 var formData = new FormData(formElement); formData.append("name", nameValue);request.send(formData);
- 上传进度
var req = new XMLHttpRequest();req.addEventListener("progress", updateProgress, false); req.open(); ... // progress on transfers from the server to the client (downloads) function updateProgress(evt) { if (evt.lengthComputable) { var percentComplete = evt.loaded / evt.total; ... } else { // Unable to compute progress information since the total size is unknown } } </pre>
实现var uploadFile = function(file) { var loadEnd = function() { content.className = "bg loading"; var request = new XMLHttpRequest(); request.open('POST', "actionURL", true);var formData = new FormData(); formData.append('upload',file); request.send(formData); request.onload = function () { content.className = "bg"; }; request.onprogress = function (evt) { if (evt.lengthComputable) { var percentComplete = evt.loaded / evt.total; } else { // Unable to compute progress information since the total size is unknown } } }; var reader = new FileReader(); // Firefox 3.6, WebKit if(reader.addEventListener) { reader.addEventListener('loadend', loadEnd, false); } else { reader.onloadend = loadEnd; } reader.readAsBinaryString(file);
};