Access local file with javascript

How do I access and read a local file from html+javascript page running locally

Is this possible at all? If yes, how do I read and write my text file using javascript?

Initially it looked like this was a duplicate and I voted to close. Sorry for that. My vote is locked in, and I can’t undo the closing vote. If you’re on a windows system, I have a few suggestions for you.

5 Answers 5

As is being discussed in Itay Moav’s answer, writing to a local file with a local HTML file is perhaps going to be an issue without running in an elevated privilege mode and having additional Javascript capabilities (that allow you to save local files).

However, accessing a local file from an HTML file is entirely possible. Below is some example code.

      

Hello World!

This will make an alert 1 second after the html page loads (to allow the iframe to load first), and will contain the content within the mytext.txt file.

Note, if it’s plaintext, Firefox will wrap it with a PRE element, which is why I did firstChild . Also, note the use of the BASE element, which points to your local directory with your files.

Источник

Javascript Access to File on local machine

I want to open the files located on local drive using window.open(). When i try to access the file using window.open i am getting error «Access is denied.» Would somebody help to achieve this requirement in Internet explorer 8.0? Thanks!

Читайте также:  Python two line command

2 Answers 2

You can’t. And thank God for that. Imagine how insecure the internet would’ve been if JS was able to access a client’s file-system.
Of course, IE8 has the MS specific JScript superset ( ActiveXObject ), which does enable filesystem access:

var fileHandle, fs = new ActiveXObject("Scripting.FileSystemObject"); fileHandle = fs.OpenTextFile("C:\\path\\to\\file.tmp", 1, true); fileHandle.Write('This is written to a file'); console.log(fileHandle.ReadLine());//will log what we've just written to the file 

But this is non-standard, is — I think- no longer supported either, and doesn’t work X-browser.
Here’s the documentation. At the bottom there’s a link to a more detailed overview of the properties and methods this object has to offer, as you can see, there’s a lot to choose from

How an we open using window.open method? I want to open the content using window.open. Window.open should open the content.

@user3463768: you can’t. You can’t open a file on the client’s disk using window.open . The only thing you could do using window.open is window.open(‘file://’); . But there’s no guarantee that’ll work. JS is code that is sent to the client via the network. If it were allowed to access local files willy-nilly, then that would be incredibly unsafe. you really should look into other ways to do whatever it is you are trying to do

If you are trying to load an HTML file that is hosted by your machine, then window.open(‘http://127.0.0.1/dirname/file.ext’) will work, but that requires you to have a server running

Is there any alternative for this? My files will be stored on local system. I am using HTML file upload control to read the file from local system and displaying the path in Grid when user clicks add button after browse from file system. So we show the path of the file in grid. User selects the path in grid and clicks on open button. The file should be opened or should ask for save. Any other way you think we can achieve this requirement?

@user3463768: Sounds like you’re barking up the wrong tree with choosing JavaScript. You’re talking about uploading files, which implies a server-side technology. I’d use AJAX + whatever server-side language you’re using on the server

I’m adding this answer just to be complete, but so far as Web Pages go, Elias Van Ootegem’s answer is correct: you can’t (and shouldn’t be able to) get to the local hard drive.

But .. you can isf your page is an HTA (HTML Application) :

This is essentially a web page with .hta as the extension(usually) and some extra tags to tell IE that it’s an HTA application, not a web page.

This is something that runs via the windows operating system and is so far as I’m aware only available for IE. The HTA application opens as a web page in IE, but without the usual web navigation / favourites toolbars etc.

Note that if you have a page on an internet server delivered as an HTA application, you’re likely to cause virus scanners and firewalls to pop up because this would essenstially be running a script whcih could do manything to your computer. Not good for general internert stuff at all, but might be useful in a secure environment like an intranet where the source of the application is known to be safe.

To get to the file system, you can use javascript code like this :

// set up a Fils System Object variable.. var FSO = new ActiveXObject("Scripting.FileSystemObject"); // function to read a file function ReadFile(sFile) < var f, ts; var s=""; if(FSO.FileExists(sFile)) < f = FSO.GetFile(sFile); ts = f.OpenAsTextStream(ForReading, TristateUseDefault); if (!ts.AtEndOfStream) ; ts.Close( ); > return s; > alert(ReadFile("c:\\somefilename.txt"); 

Источник

The Javascript API to Access a User’s Local Files

Historically, when working with frontend Javascript, it has not been possible to write or edit files on a user’s computer. The justification around this was that it was more secure to prevent direct access to a user’s file from the internet.

The new File System API changes that, and creates a secure way for us to change, edit and add files on a user’s computer. That means we can finally write to a user’s computer from a frontend Javascript file, as long as they give us permission.

How does it work?

There are three key functions we can use with the file systems API:

  • window.showSaveFilePicker — which allows us to save a file to a users computer, which we then have read/write access to.
  • window.showOpenFilePicker — which allows us to open an existing file on a users computer, which we can then read/write to.
  • window.showDirectoryPicker — which gives us access to a directory, which we can then read/write to.

These are all async compatible functions, so we can wait for a user’s response to each before proceeding. If they respond by giving access via the browsers dialog boxes, then we can use the response to write directly to the users disc.

An Example using showSaveFilePicker

Let’s look at an example. Below, we have a button which when the user clicks, will open a save file dialog. This dialog has a default suggested file name of ‘My First File.txt’.

let saveFile; document.getElementById('someButton').addEventListener('click', async () =>   try   saveFile = await window.showSaveFilePicker(  suggestedName: 'My First File.txt'  >);  const file = await saveFile.getFile();  const contents = await file.text();  > catch(e)   console.log(e);  > >); 

Using await saveFile.getFile() , we can get the file after it is created. Then, we can get its current contents using file.text() . Of course, since this file was just created, it will be empty.

Since we have our file, if it exists, saved in the saveFile variable, we can access it elsewhere. For example, we may use a textarea to update the file’s content:

document.getElementById('add-text').addEventListener('keyup', async(e) =>   if(typeof saveFile !== "undefined")   if ((await saveFile.queryPermission()) === 'granted')   const writable = await saveFile.createWritable();  await writable.write(document.getElementById('add-text').value);  await writable.close();  >  > >); 

To summarise what we’ve done here:

  • First, we check if saveFile is defined.
  • Then, we check if permission has been ‘granted‘ to this file.
  • Then we write the value of the textarea to the file using writable.write() .
  • Finally, we use writable.close() to end our writing.

With showOpenFilePicker instead

Sometimes, you don’t want to save a file — you want to open one that exists already. The primary purpose of these functions is to request user permission to get access to their files. As such, showOpenFilePicker has similar functionality to showSaveFilePicker .

If you need to open a file rather than save it, you can replace the save function with showOpenFilePicker to allow users to open existing files.

A Save File Demo

Below is a demo of what we’ve described so far. Click the button to create a file, and then type into the textarea. If you check the file on your computer, you’ll see it has been updated.

Note, at the time of writing this, this demo will only work in the latest versions of Chrome and Edge.

Once the file is created, as you type in this textarea, it will automatically save to your disc.

An example with showDirectoryPicker

Let’s look at another example, this time with directories. In this example, a user will select a directory.

let directory; document.getElementById('addToFolder').addEventListener('click', async () =>   try   directory = await window.showDirectoryPicker(  startIn: 'desktop'  >);  for await (const entry of directory.values())   let newEl = document.createElement('div');  newEl.innerHTML = `strong>$entry.name>strong> - $entry.kind>`;  document.getElementById('folder-info').append(newEl);  >  > catch(e)   console.log(e);  > >); 

The above will allow the user to select a directory, which we will then have access to. We will then show a list of all the files within that folder using the for loop we’ve defined above.

Creating Files and Folders

Now with access to this directory, we can create a file or directory using either getDirectoryHandle() or getFileHandle() :

// Creates a file let newFile = directory.getFileHandle('newFile.txt',  create: true >); // Creates a directory let newFile = directory.getDirectoryHandle('myNewDirectory'); 

We can also delete files and directories from directories we have access to. To do that, we simply do:

// Deletes a folder, recursively (i.e. it will delete all within it as well) directory.removeEntry('Some Directory',  recursive: true >); // Deletes a file directory.removeEntry('SomeFile.html'); 

A Directory Access Demo

When you click the button below, it will list all files and folders within your selected directory. So expect a lot of rows if you have a lot of files.

Note, again, this will only work in the latest versions of Edge and Chrome.

Now that we have access to the directory, click below to create a file inside of it.

Support

Since this is a new piece of technology, support varies from browser to browser. For Blink based browsers, support is quite broad:

Data on support for the native-filesystem-api feature across the major browsers from caniuse.com

Conclusion

The File Access API is a game changer. It allows us to have pure frontend web applications alter and edit files, which opens up all sorts of avenues for new applications.

We hope you’ve enjoyed this article. See below for some useful links:

More Tips and Tricks for Javascript

Источник

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