HTML5 Read the example of a drag-and-drop local file

Source: Internet
Author: User


After you create a custom drop target on your desktop, you can drag and drop the file from the desktop onto that target. Similar to dragging and dropping a picture or link, dropping the file from the desktop onto the browser triggers the drop event. It is also possible to read the placed file in Event.dataTransfer.files, which is a file object, just like the file object obtained through the input field.

Example:

<! DOCTYPE html>
<style type= "Text/css" >
#dropTarget {width:200px height:200px; background: #ccc; border:1px solid #999;}
</style>
<body>
<p> Please drag the file into the box below:</p>
<div id= "DropTarget" ></div>
<div id= "Output" ></div>
<script type= "Text/javascript" >
function Draghandle (event) {
var info = "",
Outputele = document.getElementById ("Output"),
Files, I, Len;
Event.preventdefault ();
if (Event.type = "Drop") {
Files = event.dataTransfer.files;
i = 0;
len = files.length;
while (I < Len) {
Info + + Files[i].name + "(" + Files[i].type + "," + files[i].size + "bytes) <br>";
i++;
}
outputele.innerhtml = info;
}
}
var Droptargetele = document.getElementById ("DropTarget");
Droptargetele.addeventlistener ("DragEnter", Draghandle, false);
Droptargetele.addeventlistener ("DragOver", Draghandle, false);
Droptargetele.addeventlistener ("Drop", Draghandle, false);
</script>
</body>

As with other drag-and-drop examples, the default behavior of DragEnter, DragOver, and drop must also be canceled here.

In the drop event, file information can be read by Event.dataTransfer.files.

The ability to read drag-and-drop files commonly used scenarios are:


Combine XMLHttpRequest and drag-and-drop files to upload. Up
View and manage local pictures.
View and manage local music.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.