Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple client-side file processing without refresh

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!

like image 776
MLister Avatar asked Sep 04 '12 18:09

MLister


2 Answers

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

like image 183
JayC Avatar answered Oct 29 '22 22:10

JayC


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.

like image 1
Azeezah M Avatar answered Oct 29 '22 22:10

Azeezah M