Table of Contents
Function Implementation
FormData
Specific code
Server side
Client code
Home Web Front-end H5 Tutorial Sample code sharing for html5 file drag and drop upload

Sample code sharing for html5 file drag and drop upload

Mar 27, 2017 pm 03:13 PM


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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

See all articles