[an error occurred while processing this directive]

JavaScript Open file

                          

In this section, you will learn how to open and read the file in JavaScript.

You can see in the given example, we have created a file component to let the user select the file to be read and a button to submit the request. For this, we have used  <input type="file">, through which we can browse the file and get the appropriate file to read. On clicking the "Open File" button, the function openFile() is called where we have used the JavaScript property window.location, which allows to access the selected file. The document.form.selectedFile.value display the text of the selected file on the browser.

Here is the code:

<html>
<h2>Read File in Javascript</h2>
<script language="JavaScript">
function openFile() {
window.location= 'file:///' + document.form.selectedFile.value;
}
</script>
<body>
<form name="form">
<input type="file" name="selectedFile">
<input type=button onClick="openFile()" value="Open File">
</form>
</body>
</html>

Output will be displayed as:

Now click the browse button and select the file:

When you click the Open File button, you will get the text of the selected file:

Download Source Code:

                          

[an error occurred while processing this directive]