html:
<form > <div class="drag-wrapper"> 请将图片拖到此处 </div> </form>
css:
<style> .drag-wrapper{ width:100%; height: 300px; border: 4px dashed lightblue; text-align: center; line-height: 300px; color: lightgrey; } .drag-wrapper img{ max-width: 80px; } </style>
js:
<script src="../js/jquery-2.2.3.min.js"></script> <script> $('.drag-wrapper').on('dragover',function(event){ event.preventDefault() }).on('drop',function(event){ event.preventDefault(); //数据在event的dataTransfer对象里 let file = event.originalEvent.dataTransfer.files[0]; //同样用fileReader实现图片上传 let fd = new FileReader(); let fileType = file.type; fd.readAsDataURL(file); fd.onload = function(){ if(/^image/[jpeg|png|gif|jpg]/.test(fileType)){ $('.drag-wrapper').append('<img src="'+this.result+'"/>') }else{ alert('仅支持拖拽图片') } } let formData = new FormData(); formData.append('file',file); }) </script>
预览: