18

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!

MLister
  • 10,022
  • 18
  • 64
  • 92
  • you might be read this [link]http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery – Anant Dabhi Sep 04 '12 at 18:52

2 Answers2

9

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

JayC
  • 7,053
  • 2
  • 25
  • 41
  • It seems the mozilla article only mentioned how to get the meta data of the files, like name, size, and type, but did not mention how to read the content of the file. –  Dec 17 '15 at 15:33
  • 3
    @ElgsQianChen That's what `FileReader` is for. An example is in the article. – JayC Dec 22 '15 at 21:18
4

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.

Azeezah M
  • 144
  • 1
  • 9