user2738206
user2738206

Reputation: 448

Is it possible to use the File System Access API to prompt to read a specific directory on the user's machine?

I would like to know if it's possible to use the File System Access API to ask for permission to read a file directory on the user's machine. I know the file system access API can give the user the ability to browse files to upload on their own, but my intention is to simplify this process by simply guessing the right directory to read from.

If the API is able to do the above, then is there a way to guess a relative directory so as to avoid needing to know the HOSTNAME of the user's machine? Details below.

Here is a demo of what I'm trying to do: User clicks the button, and then is automatically prompted from the app to read a given directory. The question then is how would I know YourName? Is there a way to access a relative directory? enter image description here enter image description here

Upvotes: 3

Views: 1376

Answers (1)

Dyllon Gagnier
Dyllon Gagnier

Reputation: 381

There are two ways to control where the file picker starts and this example demonstrates two of them:

const requestFileHandle = async (startIn?: FileSystemHandle) => {
    for (let i = 0; i < 2; i++) {
        const result = await window.showSaveFilePicker({
            types: [{
                description: "HTML file",
                accept: {
                    "text/html": [
                        ".html",
                        ".htm"
                    ]
                }
            }],
            id: SOME_ID,
            startIn
        } as any);
        console.log("Received file handle: %o", result)
        if (result.kind === "file") {
            return result;
        }
        alert("File input must be a file, not a directory.");
    }

    return await Promise.reject("Could not get file for saving.");
}

The most powerful way is via the startIn parameter to window.showSaveFilePicker. This can either be an existing handle (either a file or directory should work) or, it can be a WellKnownDirectory.

A WellKnownDirectory is defined as a string this according to the spec:

enum WellKnownDirectory {
  "desktop",
  "documents",
  "downloads",
  "music",
  "pictures",
  "videos",
};

Finally, you can specify id which must be a string <= 32 characters and:

A valid path id is a string where each character is ASCII alphanumeric or "_" or "-".

according to https://wicg.github.io/file-system-access/#valid-path-id

The first code sample is taken from my project https://github.com/slaymaker1907/TW5-browser-nativesaver/blob/main/src/saver.ts

Upvotes: 2

Related Questions