HTML5 File API can work with files on the local machine.
File API is exposed through drag and drop api.
When the user drops files on the drop zone, the files property of the DataTransfer object returns a FileList object.
We can treat this as an array of File objects.
Each element represents a file that the user has dropped.
The user can select multiple files and drop them in one go.
The following table shows the properties of the File object.
Name | Description | Returns |
---|---|---|
name | Gets the name of the file | string |
type | Gets the type of file, expressed as a MIME type | string |
size | Gets the size (in bytes) of the file | number |
The following code shows how we can use the File API to respond when the use drags files from the operating system and drops them in our drop zone.
<!DOCTYPE HTML> <html> <head> <title>Example</title> <style> body > * {float: left;} #target {border: medium double black; margin:4px; height: 75px; width: 200px; text-align: center; display: table;} #target > p {display: table-cell; vertical-align: middle;} table {margin: 4px; border-collapse: collapse;} th, td {padding: 4px}; </style> </head> <body> <div id="target"> <p id="msg">Drop Files Here</p> </div> <table id="data" border="1"> </table> /*from ww w .ja va2 s . c om*/ <script> let target = document.getElementById("target"); target.ondragenter = handleDrag; target.ondragover = handleDrag; function handleDrag(e) { e.preventDefault(); } target.ondrop = function(e) { let files = e.dataTransfer.files; let tableElem = document.getElementById("data"); tableElem.innerHTML = "<tr><th>Name</th><th>Type</th><th>Size</th></tr>"; for (let i = 0; i < files.length; i++) { let row = "<tr><td>" + files[i].name + "</td><td>" + files[i].type+ "</td><td>" + files[i].size + "</td></tr>"; tableElem.innerHTML += row; } e.preventDefault(); } </script> </body> </html>