Javascript process local file

50 lines of code

For security and privacy reasons web apps do not have direct access to the files
on the user’s device. If you need to read one or multiple local files, you can do
this through the usage of a file input and a FileReader. In this post we will take a look
at how this works through a few examples.

TL;DR

  • JavaScript does not have direct access to the local files due to security and privacy.
  • We can offer the user the possibility to select files via a file input element that we can then process.
  • The file input has a files property with the selected file(s).
  • We can use a FileReader to access the content of the selected file(s).

How it works

As JavaScript in the browser cannot access the local files from the user’s device,
we need to provide the user with a way to select one or multiple files for us to use.
This can be done with the HTML file input element:

If we want to allow the selection of multiple files, we can add the multiple attribute:

We can either use the change event of the input field to respond to a file selection
or add another UI element to let the user explicitly start the processing of the selected file.

Читайте также:  Import file utils java

Also note: The selection of a file with the input element does not upload the file anywhere,
the only thing that happens is that the file becomes available to the JavaScript on the page.

The file input has a files property that is a list (as there could be multiple selected files) of File objects.

A `File object looks like this:

Now we have the ability to select a file and see the metadata, but how can we access the file content?
To get the actual content of a selected file, we need a FileReader .

A file reader takes a File object and offers us methods to get access to the data as:

  • a string of text data
  • a data URL
  • a string of binary data
  • an ArrayBuffer containing raw binary data

In the following examples, we will use the readAsText and readAsDataURL methods to show the content of text and image files.

Example one: Reading text files

To show the file content as text, we change the change event handler:

document.getElementById('fileInput').addEventListener('change', function selectedFileChanged() < if (this.files.length === 0) < console.log('No file selected.'); return; >const reader = new FileReader(); reader.onload = function fileReadCompleted() < // when the reader is done, the content is in reader.result. console.log(reader.result); >; reader.readAsText(this.files[0]); >); 

First we make sure that there is a file that can be read. If the user cancels or otherwise
closes the file selection dialog without selecting a file, we have nothing to read and exit our function.

We then proceed to create a FileReader . The reader works asychronously in order
to not block the main thread and UI updates which is important when reading large files (like videos).

The reader emits a ‘load’ event (similar to images for example) that tells our code that the reading is finished.
The reader keeps the file content in its result property. The data in this property depends on which method we used to read the file.

In our example we read the file with the readAsText method, so the result will be a string of text.

Example two: Displaying an image from the user’s device

If we want to display images, reading the file into a string isn’t very helpful.
Conveniently the FileReader has a readAsDataURL method that reads the file into
an encoded string that can be used as the source for an element. The code is pretty much the same as previously,
with the exceptions that we read the file with readAsDataURL and display the result as an image:

document.getElementById('fileInput').addEventListener('change', function selectedFileChanged() < if (this.files.length === 0) < console.log('No file selected.'); return; >const reader = new FileReader(); reader.onload = function fileReadCompleted() < const img = new Image(); // creates an element img.src = reader.result; // loads the data URL as the image source document.body.appendChild(img); // adds the image to the body >; reader.readAsDataURL(this.files[0]); >); 

Источник

How To Read and Process Files with the JavaScript FileReader API

How To Read and Process Files with the JavaScript FileReader API

In this article, you will explore the File , FileReader , and FileReaderSync APIs.

Prerequisites

If you would like to follow along with this article, you will need:

  • An understanding of JavaScript methods, EventListener , and Promises will be helpful.
  • A code editor.
  • A modern web browser that supports File , FileReader , and FileReaderSync .

Uploading a File

First, to get a file from a user, we need to use an element:

This code will let users upload files from their machines.

Here’s an example of uploading a file using an HTML :

form enctype="multipart/form-data" action="/upload" method="post"> input id="input" type="file" /> form> 

For greater control in handling uploads, you can use JavaScript instead of an HTML to submit the files:

let file = document.getElementById('input').files[0]; let formData = new FormData(); formData.append('file', file); fetch('/upload/image', method: "POST", body: formData>); 

Using File Blob Properties

In modern browsers, Files have Blob properties and functions. These functions allows us to read the file.

  • .text() transforms the file into a stream and then into a string.
  • .stream() returns a ReadableStream .
  • .arrayBuffer() returns an ArrayBuffer that contains the blob’s data in binary form.
  • .slice() allows you to get slices of the file.

Create a new myFile.txt file with some text:

Then, create a new file-blob-example.html file:

!DOCTYPE html> html> body> input type="file" id="input" /> script> const streamToText = async (blob) =>  const readableStream = await blob.getReader(); const chunk = await readableStream.read(); return new TextDecoder('utf-8').decode(chunk.value); >; const bufferToText = (buffer) =>  const bufferByteLength = buffer.byteLength; const bufferUint8Array = new Uint8Array(buffer, 0, bufferByteLength); return new TextDecoder().decode(bufferUint8Array); >; document.getElementById('input').addEventListener('change', function(e)  let file = document.getElementById('input').files[0]; (async () =>  const fileContent = await file.text(); console.log('.text()', fileContent); const fileContentStream = await file.stream(); console.log('.stream()', await streamToText(fileContentStream)); const buffer = await file.arrayBuffer(); console.log('.buffer()', bufferToText(buffer)); const fileSliceBlob = file.slice(0, file.length); const fileSliceBlobStream = await fileSliceBlob.stream(); console.log('.slice() and .stream()', await streamToText(fileSliceBlobStream)); >)(); >); /script> /body> /html> 

Open file-blob-example.html in your web browser and add the myFile.txt file to the input . In your web developer console, you will see the file contents read out using .text() , .stream() , .buffer() , and .slice() .

Applying FileReader Lifecycle and Methods

There are 6 main events attached to FileReader:

  • loadstart : Fires when we start loading a file.
  • progress : Fires when the blob is read in memory.
  • abort : Fires when we call .abort .
  • error : Fires when an error occurs.
  • load : Fires when the read is successful.
  • loadend : Fires when the file is loaded and if error or abort didn’t get called or if load starts a new read.

To start loading our file we have four methods:

  • readAsArrayBuffer(file) : Reads the file or blob as an array buffer. One use case is to send large files to a service worker.
  • readAsBinaryString(file) : Reads the file as a binary string
  • readAsText(file, format) : Reads the file as USVString (almost like a string), and you can specify an optional format.
  • readAsDataURL(file) : This will return a URL where you can access the file’s content, it is Base64 encoded and ready to send to your server

Create a new filereader-example.html file that uses readAsDataURL() :

DOCTYPE html> html> head> style> body  background: #000; color: white; > #progress-bar  margin-top: 1em; width: 100vw; height: 1em; background: red; transition: 0.3s; > style> head> body> input type="file" id="input" /> progress value="0" max="100" id="progress-bar">progress> div id="status">div> script> const changeStatus = (status) =>  document.getElementById('status').innerHTML = status; > const setProgress = (e) =>  const fr = e.target; const loadingPercentage = 100 * e.loaded / e.total; document.getElementById('progress-bar').value = loadingPercentage; > const loaded = (e) =>  const fr = e.target; var result = fr.result; changeStatus('Finished Loading!'); console.log('Result:', result); > const errorHandler = (e) =>  changeStatus('Error: ' + e.target.error.name); > const processFile = (file) =>  const fr = new FileReader(); fr.readAsDataURL(file); fr.addEventListener('loadstart', changeStatus('Start Loading')); fr.addEventListener('load', changeStatus('Loaded')); fr.addEventListener('loadend', loaded); fr.addEventListener('progress', setProgress); fr.addEventListener('error', errorHandler); fr.addEventListener('abort', changeStatus('Interrupted')); > document.getElementById('input').addEventListener('change', (e) =>  const file = document.getElementById('input').files[0]; if (file)  processFile(file); > >); script> body> html> 

Open filereader-example.html in your web browser and add the myFile.txt file to the input . A progress bar will appear on the screen as the file is processed. If it loads successfully, it will indicate ‘Start Loading’ , ‘Loaded’ , and ‘Finished Loading’ .

Using FileReaderSync

FileReader is an asynchronous API because we do not want to block the main thread while reading files. For example, we don’t want our user interface to stop working when the browser is trying to read a very large file. However, there is a synchronous version of FileReader called FileReaderSync . We can only use FileReaderSync in Web Workers. Web workers have their own thread so they won’t block the main thread. FileReaderSync uses the same methods as FileReader :

  • FileReaderSync.readAsArrayBuffer()
  • FileReaderSync.readAsBinaryString()
  • FileReaderSync.readAsText()
  • FileReaderSync.readAsDataURL()

There are no event handlers because it’s synchronous.

Conclusion

In this article, you explored the File , FileReader , and FileReaderSync APIs.

Take the time to check the browser support for these features to ensure that they are applicable to the users of your projects.

Continue your learning with additional Web APIs.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

How to Read a Local File Using Javascript in Browser (.txt .json etc)

Local files can be opened and read in the browser using the Javascript FileReader object.

Quick Sample Code

   

Demo — Reading a Local Text File

This example reads a text file from the local disk :

How is File Reading Done ?

This tutorial will show how to read a file from the local filesystem by implementing the following steps :

  • Allowing the user to choose file from the device through file element.
  • Reading metadata (name, type & size) of the file using properties of the selected File object.
  • Reading contents of the file using FileReader object.

Step 1 — Allow User to Choose the File

Step 2 — Read File Metadata (Name, Type & Size) using Properties of File Object

The file selected by the user can be accessed as a File object in Javascript. The name, type & size properties of this File object gives the metadata of the chosen file.

document.querySelector("#read-button").addEventListener('click', function() < if(document.querySelector("#file-input").files.length == 0) < alert('Error : No file selected'); return; >// file selected by user let file = document.querySelector("#file-input").files[0]; // file name let file_name = file.name; // file MIME type let file_type = file.type; // file size in bytes let file_size = file.size; >); 

Step 3 — Read File Contents using FileReader Object

The contents of the selected File object is read using the FileReader object. Reading is performed asynchronously, and both text and binary file formats can be read.

  • Text files (TXT, CSV, JSON, HTML etc) can be read using the readAsText() method.
  • Binary files (EXE, PNG, MP4 etc) can be read using the readAsArrayBuffer() method.
  • Data url string can be read using the readAsDataURL() method.
document.querySelector("#read-button").addEventListener('click', function() < if(document.querySelector("#file-input").files.length == 0) < alert('Error : No file selected'); return; >// file selected by user let file = document.querySelector("#file-input").files[0]; // new FileReader object let reader = new FileReader(); // event fired when file reading finished reader.addEventListener('load', function(e) < // contents of the file let text = e.target.result; document.querySelector("#file-contents").textContent = text; >); // event fired when file reading failed reader.addEventListener('error', function() < alert('Error : Failed to read file'); >); // read file as text file reader.readAsText(file); >); 

Other FAQs on Reading a File with Javascript

The progress event of the FileReader object handles reading progress of the file.

// file read progress event reader.addEventListener('progress', function(e) < if(e.lengthComputable == true) < // percentage of the file read let percent_read = Math.floor((e.loaded/e.total)*100); console.log(percent_read + '% read'); >>); 

To get the binary data of file, the readAsBinaryString() / readAsArrayBuffer method needs to be used.

A file on a server can be read with Javascript by downloading the file with AJAX and parsing the server response.

Источник

Оцените статью