首页 > 代码库 > 文件上传于拖拽
文件上传于拖拽
上传文件
目前网页上传分为三种:
1、form提交
2、flash上传
3、插件上传
各有利弊,form提交就是没进度条,不太好取消。flash比较难搞的就是在非ie中浏览器认为flash是新窗口会话,当前网页的cookie无法传递到flash上传工具中,而针对这个一般就是用JS把当前页面中的cookie通过flash再传给后台,而对于一个后台如果使用了统一验证身份的接口那可能会有点麻烦。第三种优势很明显,比如适合如QQ空间这样用户需要大批量上传图片的,缺点也显而易见:跨浏览器上存在问题。而HTML5中的FileReader对象与as3中的很像,只不过目前as3中的方法比这个多(有兴趣可以自己去看看adobe的lives docs,对比一下两者的区别与共同点)。
页面获取多文件***
var result = document.getElementById("result");
var file = document.getElementById("file");
if(typeof FileReader == ‘undefined‘){
result.innerHTML = "<p>抱歉,你的浏览器不支持FileReader</p>";
file.setAttribute("disabled","disabled");
}
function ShowFileName(){
var file = document.getElementById("file");
for(var i =0 ;i<file.files.length;i++){
console.log(file.files[i].name);
}
}
function readAsDataURL(){
var reader = new FileReader();
var file = document.getElementById("file").files[0];
if(!/image\/\w+/.test(file.type)){
alert("请确保文件为图像文件");
return false;
}
reader.onload = function(){
var result = document.getElementById("result"); result.innerHTML+ = ‘<img src="http://www.mamicode.com/‘+this.result+‘" alt =""/>‘;
};
// reader.readAsArrayBuffer(file);
reader.readAsDataURL(file);
}
function readAsDataURL(){
var files = document.getElementById("file").files;
for (var i = files.length - 1; i >= 0; i--) {
var file = files[i];
var reader=new FileReader();
if(!/image\/\w+/.test(file.type)){
alert("请确保文件为图像文件");
return false;
}
reader.onload = function(){
var result = document.getElementById("result");
console.log(result);
result.innerHTML+ = ‘<img src="http://www.mamicode.com/‘+this.result+‘" alt =""/>‘;
};
// reader.readAsArrayBuffer(file);
reader.readAsDataURL(file);
}
}
function readAsBinaryString(){
var file = document.getElementById("file").files[0];
var reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = function(e){
var result = document.getElementById("result");
console.log(result);
result.innerHTML = this.result;
}
}
function readAsText(){
var file = document.getElementById("file").files[0];
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(e){
var result = document.getElementById("result");
result.innerHTML = this.result;
console.log(result);
}
}
<input type="file" id="file" multiple accept="*.*">
<form action="" method="" enctype="multipart/form-data">
默认情况下,enctype值为enctype=application/x-www-form-urlencoded,这种编码格式不能够上传文件,而采用multipart/form-data时,表单数据被已二进制的方式被传递出去, 无法正常用request接收,所以搞的令人很头疼。。。。
reader.onload = function(){}; //函数是由reader调用的所以this指向是reader (注意:此处的FileReader对象读取一个文件内容每读一个文件时new一个此对象)
拖动事件(html5之前只支持文本框和img的拖动)默认图像文本链接可以被拖动 draggable=“true”
dragstart->drag(拖动时持续发生)->[source]dragenter->dragover->dragdrop/dragleave
datatransfer :是拖动事件的一个属性只能在拖放事件的处理程序中被访问可以 接受text/url 但被映射为“text/plain”|"text/uri-list"用来存放
拖动文本框时浏览器会自动调用setData()将文本以”text“保存,img保存url也可以手动设置
在ondrop事件中中获取,否则之后会被销毁
属性:
dropEffect与effectAllowed 被拖动元素以及作为放置元素可以执行的操作
dropEffect被防止元素可执行的行为:
none不能把文本框防止在这
move应该把拖动元素移动到防止目标
copy把拖动元素复制到防止目标
link拖动元素是一个目标时放置目标会打开拖动元素
effectAllow被拖动元素可执行的行为 :
"uninitialized":未设置任何放置行为
"none" : 被拖动元素屋任何行为
"copy" 只允许值为“copy”的dropEffect
"link"只允许值为“link”的dropEffect
"move" 只允许值为“copy”的dropEffect
"copyLink"只允许值为“copy”和“link”的dropEffect
"copyMove" "linkMove"
"all"允许任意dropEffect
addElement(element):为拖动操作增加一个元素 clearData(format)清楚以特定格式保存的数据 setDragImage(element,x,y)指定一幅画在拖动时显示在光标下
eg:
var droptarget = document.getElementById("droptarget"),
dragme = document.getElementById("dragme"),
img = new Image();
img.src = "http://www.mamicode.com/smile.gif";
function handleEvent(event){
document.getElementById("output").innerHTML += event.type + "<br>";
switch(event.type){
case "dragstart":
event.dataTransfer.setData("Text", "Yippee!");
event.dataTransfer.setDragImage(img, 25, 25);
break;
case "dropenter":
case "dragover":
EventUtil.preventDefault(event);
break;
case "drop":
case "dragdrop":
droptarget.innerHTML = event.dataTransfer.getData("Text");
EventUtil.preventDefault(event);
}
}
EventUtil.addHandler(droptarget, "dragenter", handleEvent);
EventUtil.addHandler(droptarget, "dragover", handleEvent);
EventUtil.addHandler(droptarget, "dragleave", handleEvent);
EventUtil.addHandler(droptarget, "drop", handleEvent);
EventUtil.addHandler(dragme, "dragstart", handleEvent);
文件上传且实现拖动上传
!(function () {
var filesUpload = document.getElementById("files-upload"),
dropArea = document.getElementById("drop-area"),
fileList = document.getElementById("file-list");
function uploadFile (file) {
var li = document.createElement("li"),
div = document.createElement("div"),
img,
progressBarContainer = document.createElement("div"),
progressBar = document.createElement("div"),
reader,
xhr,
fileInfo;
li.appendChild(div);
progressBarContainer.className = "progress-bar-container";
progressBar.className = "progress-bar";
progressBarContainer.appendChild(progressBar);
li.appendChild(progressBarContainer);
/*
If the file is an image and the web browser supports FileReader,
present a preview in the file list
*/
if (typeof FileReader !== "undefined" && (/image/i).test(file.type)) {
img = document.createElement("img");
li.appendChild(img);
reader = new FileReader();
reader.onload = (function (theImg) {
return function (evt) {
theImg.src = http://www.mamicode.com/evt.target.result;
};
}(img));
reader.readAsDataURL(file);
}
// Uploading - for Firefox, Google Chrome and Safari
xhr = new XMLHttpRequest();
// Update progress bar
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
progressBar.style.width = (evt.loaded / evt.total) * 100 + "%";
}
else {
// No data to calculate on
}
}, false);
// File uploaded
xhr.addEventListener("load", function () {
progressBarContainer.className += " uploaded";
progressBar.innerHTML = "Loaded!";
}, false);
xhr.open("post", "upload/upload.php", true);
// Set appropriate headers
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", file.fileName);
xhr.setRequestHeader("X-File-Size", file.fileSize);
xhr.setRequestHeader("X-File-Type", file.type);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
alert(xhr.responseText);
xhr = null;
}
}
}
// Send the file (doh)
if ("getAsBinary" in file) {
//FF 3.5+
xhr.sendAsBinary(file.getAsBinary());
} else {
xhr.send(file);
}
// Present file info and append it to the list of files
fileInfo = "<div><strong>Name:</strong> " + file.name + "</div>";
fileInfo += "<div><strong>Size:</strong> " + parseInt(file.size / 1024, 10) + " kb</div>";
fileInfo += "<div><strong>Type:</strong> " + file.type + "</div>";
div.innerHTML = fileInfo;
fileList.appendChild(li);
}
function traverseFiles (files) {
if (typeof files !== "undefined") {
for (var i=0, l=files.length; i<l; i++) {
uploadFile(files[i]);
}
}
else {
fileList.innerHTML = "No support for the File API in this web browser";
}
}
filesUpload.addEventListener("change", function () {
traverseFiles(this.files);
}, false);
dropArea.addEventListener("dragleave", function (evt) {
var target = evt.target;
if (target && target === dropArea) {
this.className = "";
}
evt.preventDefault();
evt.stopPropagation();
}, false);
dropArea.addEventListener("dragenter", function (evt) {
this.className = "over";
evt.preventDefault();
evt.stopPropagation();
}, false);
dropArea.addEventListener("dragover", function (evt) {
evt.preventDefault();
evt.stopPropagation();
}, false);
dropArea.addEventListener("drop", function (evt) {
traverseFiles(evt.dataTransfer.files);
this.className = "";
evt.preventDefault();
evt.stopPropagation();
}, false);
})();
文件上传于拖拽