Step 1: Create a File Selection Control
First, we need to add a file input element (<input type="file">) in HTML to allow users to select local text files.
html<input type="file" id="fileInput">
Step 2: Use JavaScript to Listen for File Selection Events
When the user selects a file, we should listen for this event and then read the file's content.
javascriptdocument.getElementById('fileInput').addEventListener('change', function(event) { var file = event.target.files[0]; if (file) { var reader = new FileReader(); reader.onload = function(e) { var content = e.target.result; console.log('File content:', content); // You can process the text content as needed }; reader.readAsText(file); // Read the file content } else { console.log('No file selected'); } });
Code Explanation
- Use
document.getElementByIdto retrieve the file input element and add achangeevent listener. This event is triggered when the user selects a file. - In the event handler function, retrieve the first selected file using
event.target.files[0]. - Create a
FileReaderobject, which is an interface provided by the HTML5 File API for reading file content. - Set the
onloadevent handler for theFileReaderobject. This event is fired when the file reading completes. Within the handler, access the file's text content viae.target.result. - Call
reader.readAsText(file)to initiate reading the file content, which reads the text using the file's original encoding by default.
Example Application Scenario
Suppose you are developing a web application that requires users to upload a configuration file, parse it, and display the relevant configuration information on the page. The above method can be used to read the user-uploaded configuration file and process it for display on the web page.
The advantage of this method is that it is straightforward and does not require backend involvement for file reading; it can be handled directly on the client side. However, note that for security reasons, JavaScript can only read files selected by the user via the input field and cannot access the user's file system arbitrarily.