【前端】js+php实现图片拖拽上传

版权声明: https://blog.csdn.net/weixin_41728561/article/details/80346051
<!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';
}
 
 ?>

可以到这里下载文件

https://github.com/SmallLeaves/drag-upload-image

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页