electron + angular 下载

1.通信,使用ipcMain和ipcRender,参照electron官网

angular

main.ts

export interface IElectronService {
  download(path: string): void;
}

electron

el-main.js

//主进程代码
  ipcMain.on('download', (event, path) => {
    console.log('into download main');
    generateExcel(path);
  })

function generateExcel(path) {
// 触发will-download
  win?.webContents.downloadURL(path);
}

win?.webContents.session.on('will-download', (event, item, webContents) => {
  dialog.showOpenDialog({
    properties: ['openDirectory']
  }).then((result) => {
    if (!result.canceled) {
      // // 创建一个子窗口,专门用于展示页面,进行pdf转换
      // fs.writeFileSync(result.filePath, data);
      item.setSavePath(path.join(result.filePath, item.getFilename()))
    }
  });
  item.on('updated', (event, state) => {
    if (state === 'interrupted') {
      console.log('Download is interrupted but can be resumed')
    } else if (state === 'progressing') {
      if (item.isPaused()) {
        console.log('Download is paused')
      } else {
        console.log(`Received bytes: ${item.getReceivedBytes()}`)
      }
    }
  })
  item.once('done', (event, state) => {
    if (state === 'completed') {
      console.log('Download successfully')
    } else {
      console.log(`Download failed: ${state}`)
    }
  })
})

preload.js

contextBridge.exposeInMainWorld('electronService', {
    download: (path) => ipcRenderer.send('download', path)
    
})

下载使用will-download 则后端需要支持url下载

后端+处理中文下载失败问题

router.get('/download/:fileName', (req, res, next) => {
    var filename = req.params.fileName;
    log.info('filename download :', filename)
    // 创建可读流,读取当前项目目录下的hello.txt文件
    var rs = fs.createReadStream( path.join(__dirname , "../tmp/" , filename));
    var userAgent = (req.headers['user-agent']||'').toLowerCase();
    if(userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
        res.setHeader('Content-Disposition', 'attachment; filename=' + encodeURIComponent(filename));
    } else if(userAgent.indexOf('firefox') >= 0) {
        res.setHeader('Content-Disposition', 'attachment; filename*="utf8\'\'' + encodeURIComponent(filename)+'"');
    } else {
        /* safari等其他非主流浏览器 */
        res.setHeader('Content-Disposition', 'attachment; filename=' + new Buffer(filename).toString('binary'));
    }
    // 设置响应请求头,200表示成功的状态码,headers表示设置的请求头
    res.writeHead(200, {
        'Content-Type': 'application/force-download'
    });
    
    // 将可读流传给响应对象response
    rs.pipe(res);
})

will-download 未触发,问题待解决

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值