Home >Web Front-end >H5 Tutorial >Sample code sharing for html5 file drag and drop upload
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.
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.
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
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.
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:
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.
When testing on this machine, be careful to change the path in the code below to your own.
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.
<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!