electron 下载文件的实现(多窗口时重复触发)

electron 下载文件

electron 官网 will-download连接

这里只展现个人做法 不做解释
首先创建一个js文件 我这里为downloadFile.js 代码如下

/**
 * downloadObj为自定义信息 可自由拓展
 */
let downloadObj = {
  saveFileKey: '', // 文件的key值
  extendedFields: {}, // 扩展字段
}
exports.initDownloads = function (mainWindow) {
  mainWindow.webContents.session.on('will-download', (event, item, webContents) => {
    /**
     * 这里加一个判断 事件窗口与请求窗口id一直时下载
     * 防止你新开窗口的时候 有多个will-download事件触发
     */
    if (mainWindow.webContents.id !== webContents.id) {
      return
    }
    downloadObj.file = item
    const obj = JSON.parse(JSON.stringify(downloadObj))
    // 设置下载目录,阻止系统dialog的出现
    // item.setSavePath(savePath);
    // 下载任务更新
    item.on('updated', (e, state) => { // eslint-disable-line
      switch (state) {
        case 'progressing':
          const process = item.getTotalBytes() !== 0 ? ((+item.getReceivedBytes() / +item.getTotalBytes()) * 100).toFixed(0) : 100
          const isDestroyed = mainWindow.isDestroyed() 
          if (!isDestroyed) {
            webContents.send('download-key-progress', { process, obj }) 
          }
          break
        case 'interrupted ': // 暂停
          break
        default:
          break
      }
    });
    // 下载任务完成
    item.once('done', (e, state) => { // eslint-disable-line
      obj.saveName = item.getFilename()
      obj.savePath = item.getSavePath()
      switch (state) {
        case 'completed':
          webContents.send('download-key-done', {
            obj,
          });
          break
        default:
          break
      }
    });
  })
}
exports.downloadItemParams = function ({ saveFileKey = '', extendedFields = {} }) {
  downloadObj.saveFileKey = saveFileKey
  downloadObj.extendedFields = extendedFields
}

近日需要在使用electron下载的时候有需要在不同窗口下载文件 但我发现每次都会把所有窗口的will-download都触发 我也不是很懂其中的原理 所以我在will-download里面加了一个判断ID的代码。其次我这里下载触发的系统原生的保存文件对话框 如果你要使用自定义 请把 代码中 item.setSavePath(savePath) 注释放开

创建完成上面的文件后
需要在创建窗口的时候引入initDownloads (创建的窗口实例)
注意 每个独立新窗口打开时也要
如: downloadUtil/downloadFile为我的文件路劲加载一次initDownloads

const { initDownloads } = require('./downloadUtil/downloadFile')
mainWindow.loadURL();
initDownloads(mainWindow)

最后监听渲染进程的下载触发事件
downloadItemParams为自定义参数 可自定义拓展

ipcMain.handle("start-download-key", async (event, msg) => {
   const downloadWin = BrowserWindow.fromWebContents(event.sender) 
   downloadItemParams({
     saveFileKey: msg.saveFileKey,
     extendedFields: { message: msg.message }
   })
   downloadWin.webContents.downloadURL(msg.downloadUrL)
 })

渲染进程:

ipcRenderer.invoke("start-download-key", {
   downloadUrL: downloadUrL + `?attname=${file_name}`, // 必须
   saveFileKey: saveFileKey, // 非必须
   message: item, // extendedFields扩展 非必须
 })

菜鸟所写 不喜勿喷!!!!

你可能感兴趣的:(electron,javascript,前端)