How to Open a File in Javascript

Techwalla may earn compensation through affiliate links in this story. Learn more about our affiliate and product review process here.

JavaScript allows you to open a file, so the user can choose to save the file from the browser, or just read the file and close it. Typically, this type of programming is used to open a file when a user selects a file from a "Browse" button on the HTML page. The file selected is sent to the JavaScript code and opened using the "window.location" function.

Advertisement

Step 1

Right-click the HTML file you want to use to open the file. Click "Open With," then double-click the preferred JavaScript editor.

Video of the Day

Step 2

Create the JavaScript function. The following function opens the file selected by the user:

Advertisement

function openfile(file) { window.location = "file:///" + file; }

Step 3

Add the function to the "Browse" button on the Web page. Type the following code into the tag's code:

Advertisement

Advertisement

onclick="openfile(this.value)"

Step 4

Save the file and open it in your default Web browser. Choose a file on your system and open the file using the code.

Video of the Day

Advertisement

Advertisement

references

Report an Issue

screenshot of the current page

Screenshot loading...