Home>Article>Web Front-end> Sample code sharing for html5 file drag and drop upload

Sample code sharing for html5 file drag and drop upload

黄舟
黄舟 Original
2017-03-27 15:13:18 2116browse


html5Drag-and-drop uploading of files is an old topic. There are many examples on the Internet. The code I originally found and modified was also found online, but I just stepped on a few. After the pit, I wanted to record the process.

Function Implementation

The following mainly introduces the implementation of dragging files from outside the browser to the browser for uploading. First, some necessary basics will be introduced.

DragEvents

Drag events include the following:

  • dragstart: Fired when the user starts dragging theobject.

  • dragenter: Triggered when the mouse passes over the target element for the first time and dragging occurs. The listener for this event should indicate whether drop is allowed at this location, or the listener does not perform any operation, then drop is not allowed by default.

  • dragover: Triggered when the mouse passes over an element and drag occurs.

  • dragleave: Triggered when the mouse leaves an element and drag occurs.

  • drag: Triggered every time the mouse is moved when the object is dragged.

  • drop: This event is triggered on the element when a drop occurs at the end of the drag operation. The listener should be responsible for retrieving the dragged data and inserting it at the drop location.

  • dragend: Triggered when the mouse button is released while dragging the object.

When dragging files from outside the browser to the browser, the events that must be bound aredragoveranddrop, others can be left unbound.dragoveranddropEvent processingThe event## must be called within the function#preventDefault()function, otherwise the browser will perform default processing. For example, text-type files will be opened directly, and a download file box may pop up for non-text files.

DataTransfer Object

The drag object is used to transfer data through the drag event

event.dataTransferObtain.

  • dataTransfer.dropEffect [ = value ]: Returns the currently selected operation type. You can set a new value to modify the selected operation. Optional values are:none, copy, link, move.

  • dataTransfer.effectAllowed [ = value ]: Returns the allowed operation type, which can be modified. Optional values are:none, copy, copyLink, copyMove, link, linkMove, move, all, uninitialized.

  • dataTransfer.types: Returns a DOMString listing all formats set in the dragstart event. Also, if there are files being dragged, one of the type strings will be "Files".

  • dataTransfer.clearData( [ format ] ): Remove data in the specified format. If the argument is omitted all data is removed.

  • dataTransfer.setData(format, data): Add the specified data.

  • data = dataTransfer.getData(format): Return the specified data. If there is no such data, an empty string is returned.

  • dataTransfer.files: Returns the dragged FileList, if any.

  • dataTransfer.setDragImage(element, x, y): Use the specified element toupdate thedrag feedback, replacing the previously specified feedback ( feedback).

  • dataTransfer.addElement(element): Add the specified element to the element list used for rendering drag feedback.

In this use case, the most important thing isdataTransfer.filesAttribute, It is a list of files that the user drags into the browser. It is aFileListobject withlengthattributes. Accessible via subscript.

FormData

FormDatarepresents a form, which can be passedappend('fieldName', value)The function adds parameters to the form. The parameters can be not only strings, but also File objects or even binary data.

XMLHttpRequest level 2

The new version of the XMLHttpRequest object. The XMLHttpRequest mentioned here refers to the new version.

XMLHttpRequest can issue HTTP requests to servers with different domain names. This is called "Cross-origin resource sharing" (Cross-originresourcesharing, referred to as CORS).

Browsers have a famous same-origin policy, which is the basis of browser security. In addition to browser support, CORS also requires server consent.

XMLHttpRequest supports sending FormData directly, just like the browser performs form submission.

XMLHttpRequest also supports progress information (progressevent). Progress is divided into upload progress and download progress. The upload progress event is inXMLHttpRequest.uploadobject, the download progress event is in theXMLHttpRequestobject. Each progress event has three properties:

  • lengthComputable: Computable number of bytes uploaded

  • total: Total number of bytes

  • loaded: Number of bytes uploaded so far

In addition to progress events, the following five events are also supported:

  • loadEvent: The transfer is completed successfully.

  • abortEvent: The transfer was canceled by the user.

  • #errorEvent: An error occurred during transmission.

  • loadstartEvent: Transfer starts.

  • loadendEvent: The transfer is completed, but it is not known whether it was successful or failed.

Same asprogressevent, theevent processingfunction belonging to the upload operation is bound toXMLHttpRequest.uploadOn the object, the attribute download is directly bound to theXMLHttpRequestobject.

Specific code

When testing on this machine, be careful to change the path in the code below to your own.

Server side

The server side needs to write a Servlet to receive the uploaded form./html5/FileUploadServlet

It can be implemented quickly using the @MultipartConfig annotation of servlet3.

Client code

   drag drop upload demo <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <script type="text/javascript" src="/js/jquery.3.5.2.min.m.js"></script>
</head><div style="position: fixed;right: 0;top:100px;width: 125px; z-index:2000;"><div ><a target="_blank" rel="nofollow" href="https://www.520xingyun.com/from/188bet.php" ><img width="120px" height="550px" src="https://www.520xingyun.com/images/188_120.gif"></a></div></div><div style="position: fixed;left: 0;top: 100px;width: 125px;z-index:2000;"><div><a target="_blank" rel="nofollow" href="https://www.520xingyun.com/from/188bet.php"><img width="120px" height="550px" src="https://www.520xingyun.com/images/188_120.gif"></a></div></div> <body> <p id= "progressBarZone">请将文件拖拽进浏览器内! <br/></ p> </body> <script> var progressBarZone = document.getElementById('progressBarZone'); function sendFile(files) { if (!files || files.length < 1) { return; } var percent = document.createElement('p' ); progressBarZone.appendChild(percent); var formData = new FormData(); // 创建一个表单对象FormData formData.append( 'submit', '中文' ); // 往表单对象添加文本字段 var fileNames = '' ; for ( var i = 0; i < files.length; i++) { var file = files[i]; // file 对象有 name, size 属性 formData.append( 'file[' + i + ']' , file); // 往FormData对象添加File对象 fileNames += '《' + file.name + '》, ' ; } var xhr = new XMLHttpRequest(); xhr.upload.addEventListener( 'progress', function uploadProgress(evt) { // evt 有三个属性: // lengthComputable – 可计算的已上传字节数 // total – 总的字节数 // loaded – 到目前为止上传的字节数 if (evt.lengthComputable) { percent.innerHTML = fileNames + ' upload percent :' + Math.round((evt.loaded / evt.total) * 100) + '% ' ; } }, false); // false表示在事件冒泡阶段处理 xhr.upload.onload = function() { percent.innerHTML = fileNames + '上传完成。 ' ; }; xhr.upload.onerror = function(e) { percent.innerHTML = fileNames + ' 上传失败。 ' ; }; xhr.open( 'post', 'http://cross.site.com:8080/html5/FileUploadServlet' , true); xhr.send(formData); // 发送表单对象。 } document.addEventListener("dragover", function(e) { e.stopPropagation(); e.preventDefault(); // 必须调用。否则浏览器会进行默认处理,比如文本类型的文件直接打开,非文本的可能弹出一个下载文件框。 }, false); document.addEventListener("drop", function(e) { e.stopPropagation(); e.preventDefault(); // 必须调用。否则浏览器会进行默认处理,比如文本类型的文件直接打开,非文本的可能弹出一个下载文件框。 sendFile(e.dataTransfer.files); }, false); </script> </html></pre>
      <p style="font: 14px/25.2px Helvetica, Tahoma, Arial, sans-serif; margin: 0px; padding: 0px; text-align: left; color: #000000; text-transform: none; text-indent: 0px; letter-spacing: normal; word-spacing: 0px; white-space: normal; orphans: 2; widows: 2; font-size-adjust: none; font-stretch: normal; background-color: #ffffff; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px;"></p>
      <p style="font: 14px/25.2px Helvetica, Tahoma, Arial, sans-serif; margin: 0px; padding: 0px; text-align: left; color: #000000; text-transform: none; text-indent: 0px; letter-spacing: normal; word-spacing: 0px; white-space: normal; orphans: 2; widows: 2; font-size-adjust: none; font-stretch: normal; background-color: #ffffff; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px;">If the above codes are all deployed on the same website, there is no problem. But the upload operation I want to do is to transfer the file to another website, and a pitfall arises.</p>
      <p style="font-style: normal; font-variant: normal; font-weight: normal; font-size: 14px; line-height: 25.2px; font-family: Helvetica, Tahoma, Arial, sans-serif; margin: 0px; padding: 0px; text-align: left; color: rgb(0, 0, 0); text-transform: none; text-indent: 0px; letter-spacing: normal; word-spacing: 0px; white-space: normal; orphans: 2; widows: 2; font-stretch: normal; background-color: rgb(255, 255, 255); text-size-adjust: auto; -webkit-text-stroke-width: 0px;"></p>
      <p>The above is the detailed content of Sample code sharing for html5 file drag and drop upload. For more information, please follow other related articles on the PHP Chinese website!</p>
     </div>
     <div class="nphpQianMsg">
      <div class="clear"></div>
     </div>
     <div class="nphpQianSheng">
      <span>Statement:</span>
      <div>
       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
      </div>
     </div>
    </div>
    <div class="nphpSytBox">
     <span>Previous article:<a class="dBlack" title="Detailed introduction to HTML5 File api to implement breakpoint resumption" href="//m.sbmmt.com/m/faq/359032.html">Detailed introduction to HTML5 File api to implement breakpoint resumption</a></span>
     <span>Next article:<a class="dBlack" title="Detailed introduction to HTML5 File api to implement breakpoint resumption" href="//m.sbmmt.com/m/faq/359036.html">Detailed introduction to HTML5 File api to implement breakpoint resumption</a></span>
    </div>
    <div class="nphpSytBox2">
     <div class="nphpZbktTitle">
      <h2>Related articles</h2>
      <em><a href="//m.sbmmt.com/m/article.html" class="bBlack"><i>See more</i><b></b></a></em>
      <div class="clear"></div>
     </div>
     <ul class="nphpXgwzList">
      <li><b></b><a href="//m.sbmmt.com/m/faq/348281.html" title="AlloyTouch full-screen scrolling plug-in creates a smooth H5 page in 30 seconds" class="aBlack">AlloyTouch full-screen scrolling plug-in creates a smooth H5 page in 30 seconds</a>
       <div class="clear"></div></li>
      <li><b></b><a href="//m.sbmmt.com/m/faq/348372.html" title="HTML5 actual combat and analysis of touch events (touchstart, touchmove and touchend)" class="aBlack">HTML5 actual combat and analysis of touch events (touchstart, touchmove and touchend)</a>
       <div class="clear"></div></li>
      <li><b></b><a href="//m.sbmmt.com/m/faq/348373.html" title="Detailed explanation of image drawing examples in HTML5 canvas 9" class="aBlack">Detailed explanation of image drawing examples in HTML5 canvas 9</a>
       <div class="clear"></div></li>
      <li><b></b><a href="//m.sbmmt.com/m/faq/348374.html" title="Regular expressions and new HTML5 elements" class="aBlack">Regular expressions and new HTML5 elements</a>
       <div class="clear"></div></li>
      <li><b></b><a href="//m.sbmmt.com/m/faq/348469.html" title="How to combine NodeJS and HTML5 to drag and drop multiple files to upload to the server" class="aBlack">How to combine NodeJS and HTML5 to drag and drop multiple files to upload to the server</a>
       <div class="clear"></div></li>
     </ul>
    </div>
   </div>
   <div class="nphpFoot">
    <div class="nphpFootBg">
     <ul class="nphpFootMenu">
      <li><a href="//m.sbmmt.com/m/"><b class="icon1"></b><p>Home</p></a></li>
      <li><a href="//m.sbmmt.com/m/course.html"><b class="icon2"></b><p>Course</p></a></li>
      <li><a href="//m.sbmmt.com/m/wenda.html"><b class="icon4"></b><p>Q&A</p></a></li>
      <li><a href="//m.sbmmt.com/m/login"><b class="icon5"></b><p>My</p></a></li>
      <div class="clear"></div>
     </ul>
    </div>
   </div>
   <div class="nphpYouBox" style="display: none;">
    <div class="nphpYouBg">
     <div class="nphpYouTitle">
      <span onclick="$('.nphpYouBox').hide()"></span>
      <a href="//m.sbmmt.com/m/"></a>
      <div class="clear"></div>
     </div>
     <ul class="nphpYouList">
      <li><a href="//m.sbmmt.com/m/"><b class="icon1"></b><span>Home</span>
        <div class="clear"></div></a></li>
      <li><a href="//m.sbmmt.com/m/course.html"><b class="icon2"></b><span>Course</span>
        <div class="clear"></div></a></li>
      <li><a href="//m.sbmmt.com/m/article.html"><b class="icon3"></b><span>Article</span>
        <div class="clear"></div></a></li>
      <li><a href="//m.sbmmt.com/m/wenda.html"><b class="icon4"></b><span>Q&A</span>
        <div class="clear"></div></a></li>
      <li><a href="//m.sbmmt.com/m/dic.html"><b class="icon6"></b><span>Dictionary</span>
        <div class="clear"></div></a></li>
      <li><a href="//m.sbmmt.com/m/course/type/99.html"><b class="icon7"></b><span>Manual</span>
        <div class="clear"></div></a></li>
      <li><a href="//m.sbmmt.com/m/xiazai/"><b class="icon8"></b><span>Download</span>
        <div class="clear"></div></a></li>
      <li><a href="//m.sbmmt.com/m/faq/zt" title=""><b class="icon12"></b><span>Topic</span>
        <div class="clear"></div></a></li>
      <div class="clear"></div>
     </ul>
    </div>
   </div>
   <div class="nphpDing" style="display: none;">
    <div class="nphpDinglogo">
     <a href="//m.sbmmt.com/m/"></a>
    </div>
    <div class="nphpNavIn1">
     <div class="swiper-container nphpNavSwiper1">
      <div class="swiper-wrapper">
       <div class="swiper-slide">
        <a href="//m.sbmmt.com/m/">Home</a>
       </div>
       <div class="swiper-slide">
        <a href="//m.sbmmt.com/m/article.html" class="hover">Article</a>
       </div>
       <div class="swiper-slide">
        <a href="//m.sbmmt.com/m/wenda.html">Q&A</a>
       </div>
       <div class="swiper-slide">
        <a href="//m.sbmmt.com/m/course.html">Course</a>
       </div>
       <div class="swiper-slide">
        <a href="//m.sbmmt.com/m/faq/zt">Topic</a>
       </div>
       <div class="swiper-slide">
        <a href="//m.sbmmt.com/m/xiazai">Download</a>
       </div>
       <div class="swiper-slide">
        <a href="//m.sbmmt.com/m/game">Game</a>
       </div>
       <div class="swiper-slide">
        <a href="//m.sbmmt.com/m/dic.html">Dictionary</a>
       </div>
       <div class="clear"></div>
      </div>
     </div>
     <div class="langadivs">
      <a href="javascript:;" class="bg4 bglanguage"></a>
      <div class="langadiv">
       <a onclick="javascript:setlang('zh-cn');" class="language course-right-orders chooselan " href="javascript:;"><span>简体中文</span><span>(ZH-CN)</span></a>
       <a onclick="javascript:;" class="language course-right-orders chooselan chooselanguage" href="javascript:;"><span>English</span><span>(EN)</span></a>
       <a onclick="javascript:setlang('zh-tw');" class="language course-right-orders chooselan " href="javascript:;"><span>繁体中文</span><span>(ZH-TW)</span></a>
       <a onclick="javascript:setlang('ja');" class="language course-right-orders chooselan " href="javascript:;"><span>日本語</span><span>(JA)</span></a>
       <a onclick="javascript:setlang('ko');" class="language course-right-orders chooselan " href="javascript:;"><span>한국어</span><span>(KO)</span></a>
       <a onclick="javascript:setlang('ms');" class="language course-right-orders chooselan " href="javascript:;"><span>Melayu</span><span>(MS)</span></a>
       <a onclick="javascript:setlang('fr');" class="language course-right-orders chooselan " href="javascript:;"><span>Français</span><span>(FR)</span></a>
       <a onclick="javascript:setlang('de');" class="language course-right-orders chooselan " href="javascript:;"><span>Deutsch</span><span>(DE)</span></a>
      </div>
     </div>
    </div>
   </div>
   <!--顶部导航 end-->
  </div>
  <link rel="stylesheet" id="_main-css" href="//m.sbmmt.com/m/static/css/viewer.min.css" type="text/css" media="all">
 </body>
</html>