HTML5 Development Drag-and-drop file upload

Source: Internet
Author: User

Drag&drophandling of drag and drop functions


About HTML5 drag -and-drop file upload, in fact, there are many overseas sites have such applications, the earliest introduction of drag-and-drop upload application is Gmail, it supports the standard browser to drag local files to the browser as an attachment to the message sent, But its implementation in the use of HTML5 function, mainly through the new version of the browser to implement, IE is still a lot weaker.

DraggingThe following HTML5 technologies are used primarily for uploading applications:DRAG&DROP:HTML5 is based on the drag-and-drop event mechanism.
File API: It is convenient for the WEB application to access the files object, the document API includes FileList, Blob, file, FileReader, URI scheme, this article mainly explains the FileList and FileReader in the drag-and-drop upload Mouth.
Formdata:formdata is a new interface based on XMLHttpRequest Level 2, which makes it easy for Web applications to emulate form form data, and it is important that it supports binary stream data for files, so that we can implement AJAX to send file data back-end. HTML5 Drag & Drop Events

In the past, we wanted to achieve the drag-and-drop effect in the Web, basically using the DOM event model of MouseDown, MouseMove, MouseUp event monitoring to simulate the drag effect, in order to achieve real-time drag-and-drop movement effect, but also keep getting the mouse coordinates, Also need to constantly modify the location of the elements, code to heap a lot, and the performance is also very bad (constantly modify the location of the element will cause the page reflow, unless absolutely positioning), now has the HTML5 native drag & Drop drag events, it is really convenient for many, with "multiplier" To describe is never too.
Drag & Drop 包括以下事件:
dragstart: 要被拖拽的元素开始拖拽时触发,这个事件对象是被拖拽元素
dragenter: 拖拽元素进入目标元素时触发,这个事件对象是目标元素
dragover: 拖拽某元素在目标元素上移动时触发,这个事件对象是目标元素
dragleave: 拖拽某元素离开目标元素时触发,这个事件对象是目标元素
dragend: 在drop之后触发,就是拖拽完毕时触发,这个事件对象是被拖拽元素
drop: 将被拖拽元素放在目标元素内时触发,这个事件对象是目标元素

To complete a successful page element drag-and-drop behavior event procedure:
dragstart–> dragenter–> dragover–> drop–> dragend

To achieve drag-and-drop, the home page needs to block browser default behavior, altogether four events.

$ (document). On ({dragleave:function(e) {//drag away fromE.preventdefault (); $ ('. Dashboard_target_box '). Removeclass (' over ')); }, Drop:function(e) {//drag and drop backE.preventdefault (); }, DragEnter:function(e) {//dragged intoE.preventdefault (); $ ('. Dashboard_target_box '). addclass (' over ')); }, DragOver:function(e) {//drag and drop them.E.preventdefault (); $ ('. Dashboard_target_box '). addclass (' over ')); }});

Get file data HTML5 files API

The FileList interface in the file API, which obtains a list of local files in two main ways:
One is the form of < input type= "file" >,
One is the file information that is passed by the E.datatransfer.files drag event


var fileList = e.datatransfer.files;

Using the files method will fetch data to the array of dragged files, each file occupies an index of an array, and if the index does not have file data, a null value will be returned. The number of files can be obtained through the length property.

var filenum = filelist.length;

Determine file type

Filelist[0].type.indexof (' image ');

FormData simulation form for Ajax file upload

File.getasbinary get file stream is very simple, but to upload data, it is necessary to simulate the form of data format, first look at the simulation of the form of the JS code, formdata simulation form data is more concise, do not bother to spell the string, but directly to the data append to The Formdata object can be

New XMLHttpRequest (); Xhr.open (true); Xhr.setrequestheader ("X-requested-with", " XMLHttpRequest "); var New FormData (); Fd.append (' ff ', filelist[0]); Xhr.send (FD) ;

Demo Address:

Click Upload: Test site!!!
The front-end code is as follows:

<script src= "Http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" ></script><style >. dashboard_target_box {width:500px;    height:300px;    border:3px dashed #F53708; Text-Align:center;    Position:absolute; Z-index:2000; Top:0; Left:0; Cursor:pointer}.dashboard_target_box.over {border:3px Dashed #000; Background: #ffa}.dashboard_target_messages_container {display:inline-Block; margin:12px0 0;    position:relative; Text-Align:center;    height:44px;    Overflow:hidden; Z-index:2000}.dashboard_target_box_message {position:relative;    MARGIN:4PX Auto; font:15px/18px Helvetica, Arial, Sans-serif; font-size:15px; color:#999; Font-Weight:normal;    width:150px; Line-Height:20px}.dashboard_target_box.over #dtb-MSG1 {color:#000; Font-Weight:bold}.dashboard_target_box.over #dtb-MSG3 {color: #ffa; Border-color: #ffa} #dtb-msg2 {color:orange} #dtb-MSG3 {display:block; Border-top:1px #EEE dotted; padding:8px 24px}</style><script>$ (document). Ready (function(){   //design a more popular sliding style$ (' #drop_zone_home '). Hover (function(){            $( This). Children (' P '). Stop (). Animate ({top: ' 0px '},200); },function(){            $( This). Children (' P '). Stop (). Animate ({top: ' -44px '},200);                        }); //To implement drag-and-drop, the home page needs to block browser default behavior, a four event. $ (document). On ({dragleave:function(e) {//drag away fromE.preventdefault (); $('. Dashboard_target_box '). Removeclass (' over ')); }, Drop:function(e) {//drag and drop backE.preventdefault (); }, DragEnter:function(e) {//dragged intoE.preventdefault (); $('. Dashboard_target_box '). addclass (' over ')); }, DragOver:function(e) {//drag and drop them.E.preventdefault (); $('. Dashboard_target_box '). addclass (' over '));                }        }); //implementation of ================ upload        varbox = document.getElementById (' Target_box ');//get to the box bodyBox.addeventlistener ("Drop",function(e) {e.preventdefault ();//Cancel default Browser drag effect                        varFileList = E.datatransfer.files;//get File Object            //Filelist.length is used to get the length of the file (in fact, the number of files)                        //detects if dragging a file to a page is an action            if(Filelist.length = = 0){                $('. Dashboard_target_box '). Removeclass (' over ')); return; }            //test file is not a picture            if(Filelist[0].type.indexof (' image ') = = =-1){                $('. Dashboard_target_box '). Removeclass (' over ')); Alert ("Not a valid picture file!" "); return; }                        //var img = Window.webkitURL.createObjectURL (filelist[0]);            //drag pictures to the browser, you can implement the preview functionXHR=NewXMLHttpRequest (); Xhr.open ("Post", "html5.php",true); Xhr.setrequestheader ("X-requested-with", "XMLHttpRequest"); varFD =NewFormData (); Fd.append (' FF ', filelist[0]);            Xhr.send (FD); varpicsize=filelist[0].size/1024; $ ("#Lists"). html (' <strong> ' + filelist[0].name + ' </strong> (' + (Filelist[0].type | | "N/a") + ')-' + picsize.tofixed (2) + ' KB <a href= "pic/' +filelist[0].name+ '" target= "_blank" > View pictures </a> '); },false); });</script><div id= "Target_box" class= "Dashboard_target_box" > <div id= "drop_zone_home" class= " Dashboard_target_messages_container "> <p id=" dtb-msg2 "class=" Dashboard_target_box_message "style=" top:-44px "> Choose your picture <br>Start uploading</p> <p id= "DTB-MSG1" class= "Dashboard_target_box_message" style= "top:-44px" > Drag pictures to <br>here</p> </p> </div> <div id= "Lists" ></div></div>

HTML5 Development Drag-and-drop file upload

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.