Reputation: 10300
What is a clean and simple JavaScript
solution for the below use case:
On a web page, user selects and uploads a text file from her local filesystem, but instead of loading the file to a server, the client-side javascript code opens and processes the content of the file, and writes the results to the same page without refreshing the page.
Note: I don't need to persist the content of the file - if the user closes the page then the content is lost and that is fine. Everything should happen on the page on the client side - no need to touch the server.
If there is some lightweight JQuery
plug-in for this, would love to know!
Upvotes: 20
Views: 14129
Reputation: 174
For convenience, here's an example opening and printing a text file:
<input type='file' id='file-input' />
let fileInput = document.getElementById('file-input')
fileInput.onchange = () => {
const reader = new FileReader()
reader.onload = (e) => console.log('file contents:', e.target.result)
for (let file of fileInput.files) {
reader.readAsText(file)
}
}
The link JayC provided also has examples for readAsBinary and readAsDataURL.
Upvotes: 7
Reputation: 7141
What you're talking about is the HTML5 File API. I'm not sure what is the best link to describe it, but this might help. https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
Upvotes: 11