Setting a variable to the contents of a text file

79 Views Asked by At

In JavaScript, I have been trying to make a function that sets the innerHTML of a paragraph element into a local .txt file's contents. So I want to extract the text from a file into a paragraph on the webpage.

I have done some research, but none of the techniques worked.

1

There are 1 best solutions below

3
Mahesh Prajapati On

I have created a JavaScript example as per your requirement. try it:

function readTextFile() {
        var fileAttach = document.getElementById('fileAttach');

        if (fileAttach.files.length > 0) {
            var file = fileAttach.files[0];
            var reader = new FileReader();

            reader.onload = function (e) {
                var fileTxt = e.target.result;
                var container = document.getElementById('fileTxt');
                var lines = fileTxt.split('\n');
                lines.forEach(function (line) {
                    if (line.trim() !== '') {
                        var paragraph = document.createElement('p');
                        paragraph.textContent = line;
                        container.appendChild(paragraph);
                    }
                });
            };
            reader.readAsText(file);
        } else {
            alert('Please select a file.');
        }
    }
    document.getElementById('fileAttach').addEventListener('change', readTextFile);
<input type="file" id="fileAttach" />
<div id="fileTxt"></div>