1. 程式人生 > >【前端】js+php實現圖片拖拽上傳

【前端】js+php實現圖片拖拽上傳

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>拖拽圖片上傳</title>
</head>
<body>
	<style type="text/css">
		* {
			margin: 0;
			padding: 0;
			list-style: none;
		}
		#box {
			height: 300px;
			width: 800px;
			margin: 10px auto;
			background: #F0F8FF;
			padding: 50px;
		}
	</style>
<div id="box"></div>
</body>
</html>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
	var box = document.getElementById('box');
	box.ondragover=function(e){
		e.preventDefault();
	}
	box.ondrop=function(e){
		e.preventDefault();
		var file = e.target.files?e.target.files[0]:e.dataTransfer.files[0];
		var f = e.dataTransfer.files[0];
		fileType = f.type;
		fileSize = f.size;
		reader = new FileReader();
		var maxsize = 20480;
		var reg = /(image)/;
		if(!reg.test(fileType)){
			alert('不是正確的資料型別!');
			return false;
		}
		if(fileSize>maxsize*1024){
			alert('素材大於'+maxsize+'KB');
			return false;
		}
		var fr = new FileReader();
		fr.readAsDataURL(f);
		fr.onload=function(e){
			var Url = this.result;
			box.innerHTML+='<img src="'+Url+'" alt="" width="200" height="200" style="margin:10px;">';
		}
		var form = new FormData();
    	form.append("file", f);
		$.ajax({
			type:"post",
			url:"upload1.php",
			data:form,
			processData:false,
			contentType:false,
			success:function(data){
				if(data == 1){
					alert('上傳成功');
				}
			}
		});
	}
</script>

upload1.php

<?php 
 
header("Content-Type:text/html;charset=UTF-8");
if(is_uploaded_file($_FILES['file']['tmp_name'])){
    move_uploaded_file($_FILES['file']['tmp_name'], "./drag_uploads/".iconv("UTF-8", "GBK", $_FILES['file']['name']));
    echo '1';
}
 
 ?>

可以到這裡下載檔案