upload.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
a{
cursor: pointer;
}
.d1{
width: 80%;
height: 200px;
background: #ddd;
}
.d2{
display: none;
}
#d1_content{
width: 75%;
height: 200px;
}
#a_upload{
}
img{
height: 50px;
margin-right: 20px;
}
</style>
</head>
<body>
<div class="d1">
<div id="d1_content"></div>
</div>
<div class="d2">
<input type="file" name="mypic" style="display:none;">
</div>
<a id="a_upload">上传</a>
<script src="js/jquery.min.js"></script>
<script src="js/ajax.js"></script>
<script>
//拖动上传图片
function getId(id){
return document.getElementById(id);
}
$(document).on({
dragenter:function(e){e.preventDefault()},
dragover:function(e){e.preventDefault()},
dragleave:function(e){e.preventDefault()},
drop:function(e){e.preventDefault()},
});
var drop_area=getId("d1_content");
//ondrop 事件在可拖动元素或选取的文本放置在目标区域时触发。
var fd=null,fd1=null,fd2=null,fd3=null,fd4=null;
var count=0;
drop_area.ondrop=function(e){
e.preventDefault();
var fileInfo=e.dataTransfer.files;
var size=Math.ceil(fileInfo[0].size/1024);
if(size>2048){
alert("上传图片太大,不能超过2MB");
return;
}
var type=fileInfo[0].type.indexOf("image");
if(type==-1){
alert("只能上传图片格式的文件");
return;
}
var img=window.URL.createObjectURL(fileInfo[0]);
var html=`<img src="${img}" />`;
var his_html=$("#d1_content").html();
$("#d1_content").html(his_html+html);
switch(count){
case 0:
fd=new FormData();
//这里fd会缓存图片相关信息
fd.append("mypic",fileInfo[0]);
break;
case 1:
fd1=new FormData();
fd1.append("mypic",fileInfo[0]);
break;
case 2:
fd2=new FormData();
fd2.append("mypic",fileInfo[0]);
break;
case 3:
fd3=new FormData();
fd3.append("mypic",fileInfo[0]);
break;
case 4:
fd4=new FormData();
fd4.append("mypic",fileInfo[0]);
break;
}
++count;
}
a_upload.onclick=function(e){
e.preventDefault();
for(var i=0;i<count;i++){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
console.log(xhr.responseText);
}
xhr.open("POST","upload.php",true);
xhr.setRequestHeader("X-Requested-With",
"XMLHttpRequest");
switch(i){
case 0:
xhr.send(fd);
break;
case 1:
xhr.send(fd1);
break;
case 2:
xhr.send(fd2);
break;
case 3:
xhr.send(fd3);
break;
case 4:
xhr.send(fd4);
break;
}
}
}
</script>
</body>
</html>
注:需要引入JQ。
ajax.js:
//封装适合各种情况的简化版ajax函数
function ajax({//利用解构,获取将来参数对象中每个属性值
type,//请求类型: "get"||"post"
url,//请求的url地址: "xxx.php"
data,//请求携带的参数: "变量1=值&..."
dataType,//服务器端返回值类型: "json"||"text"
}){
//服务器端返回值类型默认为text
dataType=dataType||"text";
//只要远程请求,必有延迟,只要延迟,比用promise等待完成后,才执行后续操作
return new Promise(function(resolve){//.then()
//AJAX 4步/5步:
var xhr=new XMLHttpRequest();//1.获得xhr对象
//如果是get请求,且传入了data参数,才需要拼接url和data为get请求的完整地址
if(type.toLowerCase()=="get"&&data!==undefined)
url+="?"+data;
xhr.open(type,url,true);//2. 建立连接
//3. 设置请求状态回调函数
xhr.onreadystatechange=function(){
//如果请求完成,且成功!
if(xhr.readyState==4&&xhr.status==200){
//如果服务器端响应类型不是json,则调用后续resolve操作,并传入原始responseText,做后续处理
if(dataType.toLowerCase()!="json")
resolve(xhr.responseText);
else//如果服务器端响应类型是json,则自动调用JSON.parse转为js对象,再交给resolve函数做后续处理
resolve(JSON.parse(xhr.responseText));
}
}
//只有type为post,才需要设置请求头
if(type.toLowerCase()=="post")
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//只有type为post,才需要send时,传入参数
xhr.send(type.toLowerCase()=="post"?data:null);
})
}
init.php:
<?php
$conn=mysqli_connect('127.0.0.1','root','','upload',3306);
mysqli_query($conn,"SET NAMES UTF8");
?>
upload.php:
<?php
require("init.php");
$rs=empty($_FILES);
if($rs){
echo '{"code":-1,"msg":"没有上传文件"}';
exit;
}
$picname=$_FILES["mypic"]["name"];
$picsize=$_FILES["mypic"]["size"]/1000;
$type=strtolower(strstr($picname,"."));
if($type!=".jpg"&&$type!=".gif"&&$type!=".png"){
echo '{"code":-2,"msg":"上传文件类型错误"}';
exit;
}
if($picsize>2048){
echo '{"code":-3,"msg":"上传文件过大,不能超过2MB"}';
exit;
}
$filename=time().rand(1,9999).$type;
$src=$_FILES["mypic"]["tmp_name"];
$des="uploads/".$filename;
move_uploaded_file($src,$des);
$sql="INSERT INTO upload_img(path) VALUES('$des')";
$result=mysqli_query($conn,$sql);
if($result)
echo '{"code":1,"msg":"上传成功"}';
?>
效果图:
upload.html精简代码后:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
a{
cursor: pointer;
}
.d1{
width: 80%;
height: 200px;
background: #ddd;
}
.d2{
display: none;
}
#d1_content{
width: 75%;
height: 200px;
}
#a_upload{
}
img{
height: 50px;
margin-right: 20px;
}
</style>
</head>
<body>
<div class="d1">
<div id="d1_content"></div>
</div>
<div class="d2">
<input type="file" name="mypic" style="display:none;">
</div>
<a id="a_upload">上传</a>
<script src="js/jquery.min.js"></script>
<script src="js/ajax.js"></script>
<script>
//拖动上传图片
function getId(id){
return document.getElementById(id);
}
//避免其他操作的默认事件对效果产生影响
$(document).on({
dragenter:function(e){e.preventDefault()},
dragover:function(e){e.preventDefault()},
dragleave:function(e){e.preventDefault()},
drop:function(e){e.preventDefault()},
});
var drop_area=getId("d1_content");
//ondrop 事件在可拖动元素或选取的文本放置在目标区域时触发。
var fd0=null,fd1=null,fd2=null,fd3=null,fd4=null;
var count=0;
drop_area.ondrop=function(e){
e.preventDefault();
var fileInfo=e.dataTransfer.files;
var size=Math.ceil(fileInfo[0].size/1024);
console.log("文件大小:"+size);
if(size>2048){
alert("上传图片太大,不能超过2MB");
return;
}
var type=fileInfo[0].type.indexOf("image");
if(type==-1){
alert("只能上传图片格式的文件");
return;
}
var img=window.URL.createObjectURL(fileInfo[0]);
var html=`<img src="${img}" />`;
var his_html=$("#d1_content").html();
$("#d1_content").html(his_html+html);
fd_name = "fd"+count;
window[fd_name]=new FormData();
window[fd_name].append("mypic",fileInfo[0]);
++count;
}
a_upload.onclick=function(e){
e.preventDefault();
for(var i=0;i<count;i++){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
console.log(xhr.responseText);
}
xhr.open("POST","upload.php",true);
xhr.setRequestHeader("X-Requested-With",
"XMLHttpRequest");
fd_name = "fd"+i;
xhr.send(window[fd_name]);
}
}
</script>
</body>
</html>
主要是去掉了switch,用其他方式实现。