Home > Web Front-end > H5 Tutorial > body text

Sample code sharing for html5 file drag and drop upload

黄舟
Release: 2017-03-27 15:13:18
Original
2152 people have browsed it


html5 Drag-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 the object .

  • 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 are dragover and drop, others can be left unbound. dragover anddrop Event processingThe event ## must be called within the function #prev<a href="http://www.php.cn/wiki/1074.html" target="_blank">entDefault()</a> 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.dataTransfer Obtain.

  • dataTransfer.dropEffect [ = value ]: Returns the currently selected operation type. You can set a new value to modify the selected operation. Optional values ​​are: none, <a href="http://www.php.cn/wiki/1297.html" target="_blank">copy</a>, 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 to update the drag 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 is dataTransfer.files Attribute, It is a list of files that the user drags into the browser. It is a FileList object with length attributes. Accessible via subscript.

FormData

FormData represents a form, which can be passed append('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-origin resource sharing, 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 (progress event). Progress is divided into upload progress and download progress. The upload progress event is in XMLHttpRequest.upload object, the download progress event is in the XMLHttpRequest object. 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 as progress event, the event processing function belonging to the upload operation is bound to XMLHttpRequest.uploadOn the object, the attribute download is directly bound to the XMLHttpRequest object.

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

<html>
<head>
<title> drag drop upload demo
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
</head>
<body>
       <p id= "progressBarZone">请将文件拖拽进浏览器内! <br/></ p>
</body>

<script>
var progressBarZone = document.getElementById(&#39;progressBarZone&#39;);

function sendFile(files) {
       if (!files || files.length < 1) {
             return;
      }
      
       var percent = document.createElement(&#39;p&#39; );
      progressBarZone.appendChild(percent);

       var formData = new FormData();             // 创建一个表单对象FormData
      formData.append( &#39;submit&#39;, &#39;中文&#39; );  // 往表单对象添加文本字段
      
       var fileNames = &#39;&#39; ;
      
       for ( var i = 0; i < files.length; i++) {
             var file = files[i];    // file 对象有 name, size 属性
            
            formData.append( &#39;file[&#39; + i + &#39;]&#39; , file);       // 往FormData对象添加File对象
            
            fileNames += &#39;《&#39; + file.name + &#39;》, &#39; ;
      }
      
       var xhr = new XMLHttpRequest();
      xhr.upload.addEventListener( &#39;progress&#39;,
             function uploadProgress(evt) {
                   // evt 有三个属性:
                   // lengthComputable – 可计算的已上传字节数
                   // total – 总的字节数
                   // loaded – 到目前为止上传的字节数
                   if (evt.lengthComputable) {
    percent.innerHTML = fileNames + &#39; upload percent :&#39; + Math.round((evt.loaded / evt.total)  * 100) + &#39;%
&#39; ;
                  }
            }, false); // false表示在事件冒泡阶段处理

      xhr.upload.onload = function() {
            percent.innerHTML = fileNames + &#39;上传完成。

&#39; ;
      };

      xhr.upload.onerror = function(e) {
            percent.innerHTML = fileNames + &#39; 上传失败。

&#39; ;
      };

      xhr.open( &#39;post&#39;, &#39;http://cross.site.com:8080/html5/FileUploadServlet&#39; , 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>
Copy after login

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.

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!