Javascript read from file local

Easiest way to load and read a local text file with javascript?

I have a .csv file that I wish to load that contains information that the .HTML page will format itself with. I’m not sure how to do this however, Here’s a simple image of the files: https://i.stack.imgur.com/ewjT9.png I have looked into HTML5’s FileReader and it seems like it will get the job done but it seems to require usage of input forms. I just want to load the file and be able to access the text inside and manipulate it as I see fit. This post mentions AJAX, however the thing is that this webpage will only ever be deployed locally, so it’s a bit iffy. How is this usually done?

After a bit of further research it seems that there’s no reliable cross-browser way to read a local file without user input. You’ll need a form at the very least. However, you could store the file in localStorage once you’ve read it, and only prompt for it if the localStorage doesn’t have it. That would reduce the prompting to a one-time event.

Surely there must be some way to read txt files unprompted? I understand there are some security issues from having websites access your computer’s files, but is there no way to remove that limitation and give the website the all clear, just so I can access my database of information.

4 Answers 4

Since your web page and data file are in the same directory you can use AJAX to read the data file. However I note from the icons in your image that you are using Chrome. By default Chrome prevents just that feature and reports an access violation. To allow the data file to be read you must have invoked Chrome with a command line option —allow-file-access-from-files .

An alternative, which may work for you, is to use drag the file and drop into onto your web page. Refer to your preferred DOM reference for «drag and drop files».

You can totally make an ajax request to a local file, and get its content back.

If you are using jQuery, take a look at the $.get() function that will return the content of your file in a variable. You just to pass the path of your file in parameter, as you would do for querying a «normal» URL.

I get the error message «Origin null is not allowed by Access-Control-Allow-Origin.» when using AJAX. The solution seems to be to actually host it on the web, but I’m doing this purely locally.

@sloth, browser security doesn’t allow files to access your local system. To test this you either need to install a test server and run it from that or run through a server online

You cannot make cross domain ajax requests for security purposes. That’s the whole point of having apis. However you can make an api out of the $.get request URL.

Читайте также:  Python nameerror name pip

The solution is to use YQL (Yahoo Query Language) which is a pretty nifty tool for making api calls out of virtually any website. So then you can easily read the contents of the file and use it.

You might want to look at the official documentation and the YQL Console

I also wrote a blog post specifially for using YQL for cross domain ajax requests. Hope it helps

You can try AJAX (if you do not need asynchronous processing set «async» to false. This version below ran in any browser I tried when employed via a local web server (the address contains «localhost») and the text file was indeed in the UTF-8-format. If you want to start the page via the file system (the address starts with «file»), then Chrome (and likely Safari, too, but not Firefox) generates the «Origin null is not allowed by Access-Control-Allow-Origin.»-error mentioned above. See the discussion here.

The idea to use script-files which contain the settings as variables mentioned by Phrogz might be a viable option in your scenario, though. I was using files in the «Ini»-format to be changed by users.

Источник

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.

Читайте также:  Php if несколько действий

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

Источник

JavaScript read File Reading local files with JavaScript

This is a repost from my blog 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:

 type="file" id="fileInput" multiple> 

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.

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.

 type="file" id="fileInput"> document.getElementById('fileInput').addEventListener('change', function selectedFileChanged()  console.log(this.files); // will contain information about the file that was selected. >);  

A File object looks like this:

 name: 'test.txt', // the name of the selected file size: 1024, // the size in bytes type: 'text/plain', // the assumed file type based on file extension. This might be incorrect. lastModified: 1234567890, // timestamp of the last change according to the user's system lastModifiedDate: 'Thu Jul 04 2019 09:22:51 GMT+0200 (Central European Summer Time)' // a date object for the last modified timestamp > 

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]); >); 

Источник

Read a local text file using Javascript

I have read some of the previous questions on this topic but I really need to be 100% sure! Is it possible to read from a .txt file on my local system and present it in my HTML-BODY? I have tried several functions, here is one:

 function readFile (path) < var fso = new ActiveXObject('Scripting.FileSystemObject'), iStream=fso.OpenTextFile(path, 1, false); while(!iStream.AtEndOfStream) < document.body.innerHTML += iStream.ReadLine() + '
'; > iStream.Close(); > readFile("testing.txt");

The content of the file is simply around 100 words I want to read from the text file and display in my HTML-BODY. Is this possible without having my own server?

2 Answers 2

You can use a FileReader object to read text file here is example code:

  

Text File Reader

Select a text file:
  

If you have a fixed file to read every time your application load then you can use this code :

  

Источник

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