download attribute not suggesting file extension in save dialog

不打扰是莪最后的温柔 提交于 2021-01-28 04:21:27

问题


I am using a download link and in electron, the link opens but the Save as type only shows All Files (*.*) Is there a way for electron to force a file extension in that field using just an <a> tag? This works in chrome where it shows MY_EXTENSION (*.my_extension), but in electron it does not. This is useful for if you rename the file without the extension in the new name, it will automatically add it when downloaded.

Here is what the link looks like:

<a href="/path/to/file.my_extension" download>Download File</a>

Here is what the server response looks like:

res.set('Content-disposition', 'attachment; filename=' + req.params.name + '.my_extension');
res.set('Content-Type', 'application/zip');

回答1:


You can use DownloadItem in your main process in electron to intercept the download.

Then you can call downloadItem.setSaveDialogOptions to modify the save dialog that will be displayed by electron.

In the save options you can specify the FileFilters which will control from which extensions the user can choose when saving the file.

Example:

// in your main process:
const { BrowserWindow } = require('electron');

// create the default window
let win = new BrowserWindow();

// handle download event
win.webContents.session.on('will-download', (event, item, webContents) => {
  // TODO: find out what the user is downloading and set options accordingly
  item.setSaveDialogOptions({
    filters: [
      // Set your allowed file extensions here
      {name: "My Special Filter", extensions: ["special"]},
      {name: "Images", extensions: ["jpg", "png"]
    ],
    message: "Please pick your poison"
  });
});


来源:https://stackoverflow.com/questions/59253771/download-attribute-not-suggesting-file-extension-in-save-dialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!