Home >Web Front-end >JS Tutorial >HTML5 File Drag, Drop, Analyze, Read and Upload
if (window.File && window.FileList && window.FileReader) { ... }Although Opera supports these objects, they can only be used via a standard file input — not drag and drop. Therefore, a further check is required; I suggest using the XMLHttpRequest2 upload method, e.g.
var xhr = new XMLHttpRequest(); if (xhr.upload) { ... attach drag and drop events ... }
document.getElementById("fileselect").addEventListener("change", FileSelectHandler, false);Chrome and Firefox also allow users to drag one or more files on to a chosen element. You can attach event handlers including “dragover” and “dragleave” (for changing styles) and “drop” for detecting dropped files, e.g.
document.getElementById("filedrag").addEventListener("drop", FileSelectHandler, false);
// cancel event default e.preventDefault(); // fetch FileList object var files = e.target.files || e.dataTransfer.files; // process all File objects for (var i = 0, file; file = files[i]; i++) { ... }It’s important to cancel the default event. This prevents the browser attempting to display or handle a file when it’s dropped into the window.
if (window.File && window.FileList && window.FileReader) { ... }For more information, refer to How to Open Dropped Files Using HTML5 and JavaScript.
var xhr = new XMLHttpRequest(); if (xhr.upload) { ... attach drag and drop events ... }Similarly, the readAsDataURL() method retrieves binary image data as an encoded data URL which can be passed to an image src attribute or canvas element:
document.getElementById("fileselect").addEventListener("change", FileSelectHandler, false);For more information, refer to How to Open Dropped Files Using HTML5 and JavaScript.
document.getElementById("filedrag").addEventListener("drop", FileSelectHandler, false);Note we’ve also sent the filename as an HTTP header. This is optional, but it allows us to recreate the file using its original name on the server using a language such as PHP:
// cancel event default e.preventDefault(); // fetch FileList object var files = e.target.files || e.dataTransfer.files; // process all File objects for (var i = 0, file; file = files[i]; i++) { ... }For more information, refer to How to Asynchronously Upload Files Using HTML5 and Ajax.
// process image files under 300,000 bytes if (file.type.indexOf("image") == 0 && file.size < 300000) { ... }The handler receives an event object with .loaded (the number of bytes transferred) and .total (the file size) properties. Therefore, the progress can be calculated and passed to an HTML5 progress tag or any other element, e.g.
if (file.type.indexOf("text") == 0) { var reader = new FileReader(); reader.onload = function(e) { // get file content var text = e.target.result; ... } reader.readAsText(file); }For more information, refer to How to Create Graphical File Upload Progress Bars in HTML5 and JavaScript. I hope you enjoyed this series. File drag and drop is an important feature which can transform web application usability. HTML5 finally makes it easy.
Implementing the HTML5 drag and drop feature involves a few steps. First, you need to create a drop zone, which is an area where users can drop their files. This can be any HTML element, but it must have the ‘draggable’ attribute set to true. Next, you need to add event listeners for the ‘dragover’ and ‘drop’ events. The ‘dragover’ event is fired when a dragged item is over the drop zone, and the ‘drop’ event is fired when the item is dropped. In the event handler for the ‘drop’ event, you can access the dropped files through the ‘dataTransfer.files’ property of the event object.
Both ‘dataTransfer.files’ and ‘dataTransfer.items’ are properties of the ‘dataTransfer’ object, which is associated with drag and drop events. The ‘dataTransfer.files’ property is a FileList object representing the files being dragged. This is useful when you want to handle the dropped files on the server side. On the other hand, ‘dataTransfer.items’ is a DataTransferItemList object representing all the drag data. This is useful when you want to handle different types of drag data, not just files.
If your ‘dataTransfer.files’ is empty when the ‘drop’ event is fired, it could be because you’re trying to access it in the ‘dragover’ event handler. The ‘dataTransfer.files’ property is only populated in the ‘drop’ event. Make sure you’re accessing it in the correct event handler.
You can read the contents of the dropped files using the FileReader API. First, you need to create a new FileReader object. Then, you can use the ‘readAsText’ or ‘readAsDataURL’ method to read the file contents. The ‘readAsText’ method reads the file as a text string, and the ‘readAsDataURL’ method reads the file as a data URL.
You can display a progress bar by listening to the ‘progress’ event of the XMLHttpRequest object. The ‘progress’ event is fired periodically as the upload progresses. In the event handler, you can calculate the progress percentage and update the progress bar accordingly. Make sure to set the ‘upload’ property of the XMLHttpRequest object to true to enable the ‘progress’ event.
You can handle multiple file uploads by iterating over the ‘dataTransfer.files’ property, which is a FileList object. Each item in the FileList object is a File object representing a dropped file. You can handle each file individually, for example, by reading its contents or uploading it to the server.
You can restrict the types of files that can be dropped by checking the ‘type’ property of the File objects in the ‘dataTransfer.files’ property. The ‘type’ property is a string representing the MIME type of the file. If the file type is not allowed, you can prevent the drop action by calling the ‘preventDefault’ method of the event object in the ‘drop’ event handler.
Handling drag and drop events for nested elements can be tricky because the events bubble up the DOM tree. To prevent a parent element from receiving a drag and drop event intended for a child element, you can call the ‘stopPropagation’ method of the event object in the child element’s event handler.
You can customize the appearance of the drop zone by adding a specific class to it in the ‘dragover’ event handler and removing it in the ‘dragleave’ and ‘drop’ event handlers. You can define the appearance of the class in your CSS.
Testing the drag and drop functionality can be challenging because it involves complex user interactions. However, some testing libraries, like Selenium, provide methods for simulating drag and drop actions. You can also create a mock ‘drop’ event and dispatch it to the drop zone element.
The above is the detailed content of HTML5 File Drag, Drop, Analyze, Read and Upload. For more information, please follow other related articles on the PHP Chinese website!