Javascript下载文件强制提示目标



我正在通过javascript下载文件(该文件在服务器上生成),我想强制浏览器提示用户选择文件的目的地。可能吗?例如,Chrome 作为具有默认文件夹的选项,我希望能够覆盖该选项

编辑(解释重复的问题)我认为这不是重复的,因为我知道为什么对话框没有打开,只是想问一下是否可以覆盖该行为

您无法覆盖下载行为。许多现代浏览器将任何下载保存到默认位置,而不会提示用户。这就是他们下载文件的方式,期间。您无法覆盖此设置。这是用户在浏览器首选项中的选择,是否要被提示。

是的,可以使用文件系统访问 API 覆盖该行为。API 公开了一些将覆盖浏览器行为的方法。只需在 Chrome 浏览器控制台中运行window.showOpenFilePicker()即可启动文件选取器提示。

若要覆盖下载目标提示行为,可以使用 window.showSaveFilePicker() 方法。

// ...
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);
      }
}

有关更多详细信息,请查看文档 https://web.dev/file-system-access/和 https://web.dev/browser-fs-access/

相关内容

最新更新