html5实现拖拽文件上传
html文件
[html]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-CN">
<head>
<title>HTML5拖拽上传</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<style type="text/css">
#dropzone{
width:300px;
height:300px;
border:2px dashed gray;
}
#dropzone.over {
border:2px dashed orange;
}
</style>
</head>
<body>
<h1>拖拽上传</h1>
<div id="dropzone"></div>
</body>
<script type="text/javascript">
// 负责ajax发送数据
function up(fd) {
var xhr = new XMLHttpRequest();
xhr.open('POST','upfile.php',true); // 异步传输
// xhr.upload 这是html5新增的api,储存了上传过程中的信息
xhr.upload.onprogress = function (ev) {
var percent = 0;
if(ev.lengthComputable) {
percent = 100 * ev.loaded/ev.total;
//document.getElementById('progress').innerHTML = percent;
document.getElementById('bar').style.width = percent + '%';
}
}
xhr.send(fd);
}
var dz = document.getElementById('dropzone');
dz.ondragover = function (ev) {
this.className = 'over';
return false;
}
dz.ondragleave = function (){
this.className = '';
}
dz.ondrop = function(ev) {
//console.log(ev.dataTransfer.files[0]);
var fd = new FormData();
fd.append('pic',ev.dataTransfer.files[0]);
up(fd);
return false; // 拦截拖放的正常行为
}
</script>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-CN">
<head>
<title>HTML5拖拽上传</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<style type="text/css">
#dropzone{
width:300px;
height:300px;
border:2px dashed gray;
}
#dropzone.over {
border:2px dashed orange;
}
</style>
</head>
<body>
<h1>拖拽上传</h1>
<div id="dropzone"></div>
</body>
<script type="text/javascript">
// 负责ajax发送数据
function up(fd) {
var xhr = new XMLHttpRequest();
xhr.open('POST','upfile.php',true); // 异步传输
// xhr.upload 这是html5新增的api,储存了上传过程中的信息
xhr.upload.onprogress = function (ev) {
var percent = 0;
if(ev.lengthComputable) {
percent = 100 * ev.loaded/ev.total;
//document.getElementById('progress').innerHTML = percent;
document.getElementById('bar').style.width = percent + '%';
}
}
xhr.send(fd);
}
var dz = document.getElementById('dropzone');
dz.ondragover = function (ev) {
this.className = 'over';
return false;
}
dz.ondragleave = function (){
this.className = '';
}
dz.ondrop = function(ev) {
//console.log(ev.dataTransfer.files[0]);
var fd = new FormData();
fd.append('pic',ev.dataTransfer.files[0]);
up(fd);
return false; // 拦截拖放的正常行为
}
</script>
</html>
upfile.php
[php]
echo move_uploaded_file($_FILES['pic']['tmp_name'],'./upload/' . $_FILES['pic']['name']) ? 'OK':'fail';
echo move_uploaded_file($_FILES['pic']['tmp_name'],'./upload/' . $_FILES['pic']['name']) ? 'OK':'fail';
如图:
补充:web前端 , HTML 5 ,