DEV Community

Cover image for Vanilla JS for selecting a local text file and reading its content
Toby Chui
Toby Chui

Posted on

Vanilla JS for selecting a local text file and reading its content

Image description

Recently I am working a small side project that aims to build a mechanical 4-keys macropad with the lowest cost possible. To make it more user friendly, I need to develop a website that let user load their previous config file (JSON) and allow them to continue their "graphical programming". I search online for a Javascript only solution that do the trick but it took me some time to reach what I need.

To save other's time (and make sure myself won't forget this in the future), here is how you allow user to select a text file, upload it using a File Selection Dialog and read its contents in Vanilla JS



let input = document.createElement('input');
input.type = 'file';
input.multiple = true;
input.onchange = e => { 
    let files = e.target.files; 
    for (var i = 0; i < files.length; i++){
        let read = new FileReader();
        read.readAsBinaryString(files[i]);
        read.onloadend = function(){
            //Content of the file selected
            console.log(read.result);
        }
    }
}
input.click();


Enter fullscreen mode Exit fullscreen mode

Cheers!

Top comments (0)