1 2
| <div id="drop_area" style="border:3px dashed silver;width:200px; height:200px">将图片拖拽到此</div> <button onclick="xhr2()">ajax上传</button>
|
2.禁止浏览器打开文件行为
1 2 3 4 5 6 7 8 9 10 11 12
| document.addEventListener("drop",function(e){ e.preventDefault(); }) document.addEventListener("dragleave",function(e){ e.preventDefault(); }) document.addEventListener("dragenter",function(e){ e.preventDefault(); }) document.addEventListener("dragover",function(e){ e.preventDefault(); })
|
3.拖拽,预览文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| var box = document.getElementById('drop_area'); box.addEventListener("drop",function(e){ var fileList = e.dataTransfer.files; if(fileList.length == 0){ return false; } Array.prototype.S=String.fromCharCode(2); Array.prototype.in_array=function(e){ var r=new RegExp(this.S+e+this.S); return (r.test(this.S+this.join(this.S)+this.S)); }; var video_type=["video/mp4","video/ogg"]; var fileurl = window.URL.createObjectURL(fileList[0]); if(fileList[0].type.indexOf('image') === 0){ var str="<img width='200px' height='200px' src='"+fileurl+"'>"; document.getElementById('drop_area').innerHTML=str; }else if(video_type.in_array(fileList[0].type)){ var str="<video width='200px' height='200px' controls='controls' src='"+fileurl+"'></video>"; document.getElementById('drop_area').innerHTML=str; }else{ var str="文件名字:"+fileList[0].name; document.getElementById('drop_area').innerHTML=str; } resultfile = fileList[0]; },false);
|
4.ajax上传
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| function xhr2(){ var xhr = new XMLHttpRequest(); var formData = new FormData(); formData.append('file', resultfile); xhr.open('POST', 'xhr2.php'); xhr.send(formData); xhr.onreadystatechange = function(){ if ( xhr.readyState == 4 && xhr.status == 200 ) { console.log( xhr.responseText ); } }; xhr.timeout = 10000; xhr.ontimeout = function(event){ alert('请求超时!'); } }
|
5.PHP保存文件
1 2 3 4 5
| <?php print_r($_FILES["file"]); $name = $_FILES["file"]["name"]; move_uploaded_file($_FILES["file"]["tmp_name"],iconv("UTF-8","gb2312",$name)); ?>
|
参考:https://blog.csdn.net/wjn2000414/article/details/80396056