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.
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 uploadedtotal
: Total number of bytesloaded
: Number of bytes uploaded so far
In addition to progress events, the following five events are also supported:
load
Event: The transfer is completed successfully.abort
Event: The transfer was canceled by the user.#error
Event: An error occurred during transmission.loadstart
Event: Transfer starts.loadend
Event: 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.upload
On 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('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>
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!

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

H5 improves web user experience with multimedia support, offline storage and performance optimization. 1) Multimedia support: H5 and elements simplify development and improve user experience. 2) Offline storage: WebStorage and IndexedDB allow offline use to improve the experience. 3) Performance optimization: WebWorkers and elements optimize performance to reduce bandwidth consumption.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
