DEV Community

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

Posted on

1

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)

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay