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 未触发,问题待解决