is there a way to take text from input type file and proccess the text in javascript

Viewed 48

i am trying to preview a text from a text file through input type file using javascript i tried using the file directly in my code but error is prompted saying file is undefiend but when i use file.value or print file to console an object from file is displayed

function readInsideFile()
{
         const [file] = document.querySelector('input[type=file]').files;
         console.log(file);
        const reader = new FileReader();
        
    // this will then display a text file
        var text = reader.readAsText(file);
        console.log(text);
         var firstLine = text.split('\n').shift(); // first line 
        
         var sensorsoutputfield = document.getElementById("Rectangle_8_bu");
         sensorsoutputfield.innerHTML = firstLine;
    
    
}

1 Answers

Yes, you can read files, but you must write lambda functions for reader. Use this Example

function readInsideFile()
{
     const files = document.querySelector('input[type=file]').files;
     console.log(files);
     const reader = new FileReader();
     // this will then display a text file
     reader.onload = () => {
         var content = reader.result;
         console.log(text);
         var firstLine = text.split('\n').shift(); // first line
         var sensorsoutputfield = 
         document.getElementById("Rectangle_8_bu");
         sensorsoutputfield.innerHTML = firstLine;
     }
     reader.readAsText(this.files[0]);
}
Related