Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Remember and Repopulate File Input in HTML5
Browsers do not allow you to programmatically set the value of a file <input> for security reasons. This means you cannot "remember" a previously selected file and repopulate the input on page reload using JavaScript alone. However, HTML5 introduced the Drag and Drop API along with the DataTransfer object, which provides a workaround − users can drag files onto a drop zone, and your code can process those files just like a file input would.
How Drag and Drop Works with Files
When a user drops a file onto a designated area, the browser fires a drop event. The dropped files are available through the event.dataTransfer.files property, which returns a FileList object − the same type returned by <input type="file">. You can then process these files (read, upload, display) using JavaScript.
Complete Working Example
The following example creates a drop zone where users can drag and drop files. The file name and size are displayed after dropping ?
Example
<!DOCTYPE html>
<html>
<head>
<style>
#dropZone {
width: 300px;
height: 150px;
border: 2px dashed #999;
text-align: center;
line-height: 150px;
color: #666;
font-family: Arial, sans-serif;
}
#dropZone.dragging {
border-color: #4CAF50;
background: #e8f5e9;
color: #333;
}
</style>
</head>
<body>
<div id="dropZone">Drop files here</div>
<p id="output"></p>
<script>
var target = document.getElementById('dropZone');
var output = document.getElementById('output');
// Dragover - allow drop
target.addEventListener('dragover', function(ev) {
ev.preventDefault();
target.classList.add('dragging');
});
// Drag leave - remove highlight
target.addEventListener('dragleave', function() {
target.classList.remove('dragging');
});
// Drop - process files
target.addEventListener('drop', function(ev) {
ev.stopPropagation();
ev.preventDefault();
target.classList.remove('dragging');
var files = ev.dataTransfer.files;
handleFiles(files);
});
function handleFiles(files) {
var result = '';
for (var i = 0; i < files.length; i++) {
result += 'File: ' + files[i].name +
' (' + files[i].size + ' bytes)<br>';
}
output.innerHTML = result;
}
</script>
</body>
</html>
When you open this in a browser and drag a file onto the dashed box, the drop zone highlights in green. After dropping, the file name and size are displayed below the box.
Conclusion
While you cannot programmatically repopulate a file <input> in HTML5, the Drag and Drop API provides a user-friendly alternative. By listening for dragover, dragleave, and drop events, you can accept files and process them using the DataTransfer.files property.
