1

I'm downloading a file via javascript (the file is generated on the server) and I want to force the browser to prompt the user to choose the destination of the file. Is it possible? For instance, Chrome as an option with a default folder and I want to be able to override that option

EDIT (explaining the duplicate question) I think it's not a duplicate because I know why the dialog is not opening, just want to ask if the behavior can be overriden

NunoRibeiro
  • 511
  • 2
  • 7
  • 22
  • 1
    Possible duplicate of [Prompting user to save file using a 'Save-as' dialog?](http://stackoverflow.com/questions/19679842/prompting-user-to-save-file-using-a-save-as-dialog) – online Thomas Feb 08 '16 at 10:10

2 Answers2

3

You cannot override the download behaviour. A number of modern browsers save any download into a default location without prompting the user. That's how they download files, period. You cannot override this. It's a user choice in the browser's preferences whether they want to be prompted or not.

deceze
  • 510,633
  • 85
  • 743
  • 889
3

Yes, the behavior can be overridden using the File System Access API. The API exposes some methods that will override the browser's behavior. Simply running window.showOpenFilePicker() in the Chrome Browser console will launch the file picker prompt.

To override the download destination prompt behavior, you can make use of the window.showSaveFilePicker() method.

// ...
const blob = new Blob(/*...*/);
// Use File System Access API
saveFileToDisk(blob, 'Some-File.txt')

async saveFileToDisk({blob, fileName}){
      try {
        const fileHandle = await self.showSaveFilePicker({
          suggestedName: fileName,
          types: [
            {
              description: "File",
              // ...
            },
          ],
        });
        const writeFile = async (fileHandle, contents) => {
          // Create a FileSystemWritableFileStream to write to.
          const writable = await fileHandle.createWritable();
          // Write the contents of the file to the stream.
          await writable.write(contents);
          // Close the file and write the contents to disk.
          await writable.close();
        };
        // write file
        writeFile(fileHandle, blob).then(() => console.log("FILE DOWNLOADED!!!"));
      } catch (error) {
        console.log(error);
      }
}

For more details, check out the documentation https://web.dev/file-system-access/ and https://web.dev/browser-fs-access/

  • 1
    As of late Dec 2021, showSaveFilePicker is only supported on Chrome, Edge and Opera, and only if using HTTPS. https://developer.mozilla.org/en-US/docs/Web/API/Window/showSaveFilePicker – KevinHJ Dec 27 '21 at 15:20