API+FileReader+XHR2+FormData,实现拖
2017-06-12 本文已影响0人
飞鱼_JS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>拖拽</title>
<style>
#drag_box{
width:100px;
height:100px;
border:1px solid orange;
background:#ccc;
cursor: pointer;
}
#box{
width:100%;
height:400px;
background:#eee;
margin:10px 0px;
}
#box .item{
float:left;
margin:5px;
position:relative;
}
#box .item .item-progress{
position:absolute;
left:50%;
top:50%;
width:80px;
height:80px;
transform: translate(-50%, -50%);
background:rgba(0,0,0,.6);
border-radius:40px;
color:#fff;
text-align: center;
line-height:80px;
}
#box img{
max-height: 150px;
}
.over{
border:2px dashed #ccc;
transform: scale(0.9, 0.9);
}
</style>
</head>
<body>
<h3>请把文件夹中的图片拖到下面区域</h3>
<div id="box">
</div>
<script>
//获取目标元素
var box = document.querySelector("#box");
//给目标元素绑定事件
box.addEventListener("dragenter", function(){
this.classList.add('over');
}, false);
box.addEventListener("dragleave", function(){
this.classList.remove("over");
}, false);
box.addEventListener("dragover", function(e){
e.preventDefault(); //阻止默认的动作
}, false);
box.addEventListener("drop", function(e){
e.preventDefault(); //阻止浏览器默认行为
//遍历FileList
[].forEach.call(e.dataTransfer.files, function(itemFile){
//创建imte
var itemEle = document.createElement("div");
itemEle.className = "item";
document.getElementById("box").appendChild(itemEle);
//读取文件
readImage(itemFile, itemEle);
//上传文件
uploadImage(itemFile, itemEle);
})
this.classList.remove("over"); //恢复样式
},false);
/**
* 读取图片
* @param File fileObj
* @Param element ele 要预览插入的元素
*/
function readImage(fileObj, ele) {
//创建FileReader对象
var frObj = new FileReader();
//监听读取成功
frObj.onload = function(){
var img = document.createElement("img");
img.src = frObj.result;
ele.appendChild(img);
}
//读取
frObj.readAsDataURL(fileObj);
}
/**
* 上传文件
* @param object FileObj对象
* @param element ele对象
*/
function uploadImage(fileObj, ele){
//创建FormData
var fd = new FormData();
fd.append("uploadfile", fileObj);
//创建元素
var progressEle = document.createElement("div");
progressEle.className = "item-progress";
ele.appendChild(progressEle);
progressEle.innerHTML = "0%";
//XHR
var xhr = new XMLHttpRequest();
xhr.onload = function(){
console.log(xhr.responseText);
//上传进度去掉
setTimeout(function(){
ele.removeChild(progressEle);
}, 500)
}
//上传对象
xhr.upload.onprogress = function(en){
progressEle.innerHTML = (en.loaded/en.total).toFixed(2)*100 + "%";
}
xhr.open("POST", "../uploadserver/upload.php");
xhr.send(fd);
}
</script>
</body>
</html>