Home > Web Front-end > JS Tutorial > How to implement drag-and-drop upload of images using JavaScript

How to implement drag-and-drop upload of images using JavaScript

巴扎黑
Release: 2017-08-07 16:45:53
Original
2365 people have browsed it

This article mainly introduces the js drag-and-drop function to upload images for everyone. It has certain reference value. Interested friends can refer to

to directly pull local images to your settings. After the picture is successfully uploaded, it will be ok. The specific code is as follows


<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>标题</title>
<meta name="keywords" content="">
<meta name="description" content="">
<style>
 *{margin:0; padding:0; list-style:none;}
 #box{
  width: 600px;
  height: 300px;
  background: #ccc;
  padding: 50px;
 }
</style>
</head>
<body>

 <p id="box"></p>
 
<script>
var box=document.getElementById(&#39;box&#39;);
box.ondragover=function (e){
 e.preventDefault();
}
box.ondrop=function (e){
 e.preventDefault();
 // console.log(e.dataTransfer.files[0]);
 var f=e.dataTransfer.files[0];//获取到第一个上传的文件对象
 var fr=new FileReader();//实例FileReader对象
 fr.readAsDataURL(f);//把上传的文件对象转换成url
 fr.onload=function (e){
  console.log(e);
  // var Url=e.target.result;//上传文件的URL
  var Url=this.result;//上传文件的URL
  box.innerHTML+=&#39;<img src="&#39;+Url+&#39;" alt="">&#39;;
 }
}
</script>
</body>
</html>
Copy after login

The above is the detailed content of How to implement drag-and-drop upload of images using JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template