javascripthtmlfile-system-access-api

File System Access API - open/read a file without using showOpenFilePicker()


I wonder if there is a solution to open only one file directly without using showOpenFilePicker() function?

I don't want to let other users to pick a different file but API would use only the correct one. I have a root and name of file.

FROM:

this.getFileAsText = async function () {
        var [fileHandle] = await window.showOpenFilePicker();
        var fileData = await fileHandle.getFile();
            return text = await fileData.text();
    }

TO:

this.getFileAsText = async function () {
        var [fileHandle] = await directFile(myPath/test.txt);
        var fileData = await fileHandle.getFile();
            return text = await fileData.text();
    }

thanks


Solution

  • For security reasons this cannot be done in a normal browser. You wouldn't want a site you visit on the internet be able to just open a file on your local computer. There are only three ways to get to files on the local file system, one is through the File System Access API, the other through the HTML upload button, the final one if files are dragged into the browser. All have in common that the user has to select exactly which files they want to make available to the website.

    The "correct" solution here depends on what you're trying to make; you could for instance make a browser extension if your webapp is for a small number of people. Or you could use Origin Private File System if you want to save a file from your webapp, and load it later.

    However if your idea is for a website that random people visit, and the website wants to get access to a local file on that user's file system, it is not going to work (again, for obvious reasons). (Rather, if you ever get this to work on any major browser, you should definitely tell them and probably get the largest payout ever from the browser's bug bounty program.