I want to allow users to drag and drop (or select) a file from their computer and load it into a textbox with JavaScript.
Is it possible to load a local file with JavaScript into a textbox? If yes, then how?
The HTML Drag and Drop API relies on the DOM's event model to get information on what is being dragged or dropped and to update that element on drag or drop. With JavaScript event handlers, you can turn any element into a draggable item or an item that can be dropped into.
Drag and drop file uploads happen when you drag one or more files from an underlying platform's file manager and drop them onto a web page for upload. A preview of the image indicates the upload has begun. Many JavaScript libraries create this type of drag and drop file upload feature with a few lines of code.
I think everything you would want for HTML5 is included in remy/html5demos on github.
As an example, I modified http://html5demos.com/file-api to accept text files and display them in the browser.
See the jsfiddle.
Edit
Relevant script:
// modified from http://html5demos.com/file-api
var holder = document.getElementById('holder'),
state = document.getElementById('status');
if (typeof window.FileReader === 'undefined') {
state.className = 'fail';
} else {
state.className = 'success';
state.innerHTML = 'File API & FileReader available';
}
holder.ondragover = function() {
this.className = 'hover';
return false;
};
holder.ondragend = function() {
this.className = '';
return false;
};
holder.ondrop = function(e) {
this.className = '';
e.preventDefault();
var file = e.dataTransfer.files[0],
reader = new FileReader();
reader.onload = function(event) {
console.log(event.target);
holder.innerText = event.target.result;
};
console.log(file);
reader.readAsText(file);
return false;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With