Jump to content

Read file from computer


JKowalski

Recommended Posts

The file:/// protocol would be used for this, but browsers don't allow websites to load Javascript files from your filesystem for security reasons.

Link to comment
Share on other sites

At first, you need to use a input[type=file] to get a File.

 

<input type=file id=file/>
<div id=result></div>

And then use FileReader to read file to target format, just like base64, text, buffer.

const file = document.getElementById('file').files[0]
const result = document.getElementById('result')
const reader = new FileReader
reader.addEventListener('load', () => {
    result.innerHTML = reader.result
})
reader.readAsText(file, 'UTF-8')

See: https://developer.mozilla.org/en-US/docs/Web/API/FileReader

Link to comment
Share on other sites

15 hours ago, Makwana Prahlad said:

At first, you need to use a input[type=file] to get a File.

 


<input type=file id=file/>
<div id=result></div>

And then use FileReader to read file to target format, just like base64, text, buffer.


const file = document.getElementById('file').files[0]
const result = document.getElementById('result')
const reader = new FileReader
reader.addEventListener('load', () => {
    result.innerHTML = reader.result
})
reader.readAsText(file, 'UTF-8')

See: https://developer.mozilla.org/en-US/docs/Web/API/FileReader

If you read the thread instead of just the title, the question was regarding running Javascript from a local file.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...