The following sample shows the upload Image Preview feature. The choice of pictures, in addition to using the File upload control to select pictures, you can drag and drop the picture directly into the dotted box.
1, the principle of realization
(1) In order to handle the operation of placing files, three events need to be handled: OnDragEnter, OnDragOver and OnDrop.
(2) The Readasdataurl () method is used to process the picture, and the resulting data URL is a way of representing the picture in a long string. To display a picture in a Web page, you can set the Src property of the element to the picture URL, or you can also set the Background-image property of the CSS to a picture URL (in this case)
(3) Here will display the image of the <div> background-size set to 100%, in order to reduce the picture to display all. and set the background-repeat to No-repeat, not to allow the picture to be repeatedly displayed.
<! DOCTYPE html>
<meta charset= "Utf-8" >
<title>read image</title>
<style>
#dropBox {
margin:15px;
width:250px;
height:250px;
border:5px dashed gray;
border-radius:8px;
Background:lightyellow;
background-size:100%;
Background-repeat:no-repeat;
Text-align:center;
}
#dropBox Div {
margin:75px 45px;
Color:orange;
font-size:25px;
Font-family:verdana, Arial, Sans-serif;
}
Input {
margin:15px;
}
</style>
<script>
var DropBox;
Window.onload = function () {
DropBox = document.getElementById ("DropBox");
Dropbox.ondragenter = Ignoredrag;
Dropbox.ondragover = Ignoredrag;
Dropbox.ondrop = drop;
}
function Ignoredrag (e) {
Because we're dealing with drag-and-drop, we should make sure that no other elements will get this event
E.stoppropagation ();
E.preventdefault ();
}
function Drop (e) {
Canceling event propagation and default behavior
E.stoppropagation ();
E.preventdefault ();
Get dragged in the file
var data = E.datatransfer;
var files = data.files;
A function that passes it to a real processing file
Processfiles (files);
}
function Processfiles (files) {
var file = Files[0];
var output = document.getElementById ("Fileoutput");
Create FileReader
var reader = new FileReader ();
Tell it what to do after the data is ready.
Reader.onload = function (e) {
Use an image URL to draw a Dropbox background
dropBox.style.backgroundImage = "url (' + E.target.result + ')";
};
Reading pictures
Reader.readasdataurl (file);
}
function Showfileinput () {
var fileInput = document.getElementById ("FileInput");
Fileinput.click ();
}
</script>
<body>
<div id= "DropBox" >
<div> drag and drop the picture here ...</div>
</div>
<input id= "fileInput" type= "file" onchange= "Processfiles (this.files)" >
</body>