Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Drag and Drop: Load text file in a textbox with JavaScript

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?

like image 691
Akshat Mittal Avatar asked Jul 03 '12 14:07

Akshat Mittal


People also ask

How drag and drop works in JavaScript?

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.

How do I drag and drop files to upload?

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.


1 Answers

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;
};​
like image 100
Jim Schubert Avatar answered Oct 03 '22 07:10

Jim Schubert