Electron下载生成的小程序二维码图片(非浏览器a标签下载)

javascript 复制代码
const generateMiniProgramQR = async (
    params: { scene: any; page?: any; width?: number; label?: any },
    ACCESS_TOKEN: any,
    label: any
) => {
    try {
        const url = `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${ACCESS_TOKEN}`
        
        // 渲染进程
        // const { ipcRenderer } = require('electron')

        const downloadFile = async (
            url: string,
            params: { scene: any; page?: any; width?: number | undefined; label?: any },
            filename: string
        ) => {
            try {
                const response = await axios.post(url, params, { responseType: 'arraybuffer' })
                //     //  将二进制数据通过IPC发送到主进程
                //     ipcRenderer.send('silent-download', {
                //         buffer: Buffer.from(response.data),
                //         filename: `${filename}.jpg`,
                //     })

                // 关键:转换为 Uint8Array 而非 Buffer
                const buffer = new Uint8Array(response.data)

                // 通过预加载接口发送
                window.electronAPI.downloadFile(buffer, `${filename}.jpg`)

                // 监听结果(可选)
                window.electronAPI.onDownloadResult(({ success, path, error }) => {
                    if (success) console.log('文件保存至:', path)
                    else console.error('保存失败:', error)
                })
            } catch (error) {
                console.error('下载请求失败:', error)
            }
        }
        downloadFile(url, params, label)
    } catch (error) {
        // 错误处理
        console.error('下载失败:', error)
    }
}

注意

这里用require不行,主线程默认开启contextIsolation,不允许node方式引入

javascript 复制代码
const { ipcRenderer } = require('electron')

主线程main.ts,每次修改文件,项目会自动重启

javascript 复制代码
import { app, BrowserWindow, dialog, ipcMain, shell } from 'electron'
import path from 'node:path'
import fs from 'fs'
ipcMain.on('silent-download', (event, { buffer, filename }) => {
    try {
        const downloadsPath = app.getPath('desktop'); 
        // 改为系统下载目录:app.getPath('downloads')
        const filePath = path.join(downloadsPath, filename);

        // 将 Uint8Array 转换为 Node.js Buffer
        const nodeBuffer = Buffer.from(buffer);
        fs.writeFile(filePath, nodeBuffer, (err) => {
            if (err) {
                event.sender.send('download-result', { success: false, error: err.message });
            } else {
                event.sender.send('download-result', { success: true, path: filePath });
            }
        });
    } catch (error: any) {
        event.sender.send('download-result', { success: false, error: error.message });
    }
});

preload.ts

javascript 复制代码
import { ipcRenderer, contextBridge } from 'electron'

contextBridge.exposeInMainWorld('electronAPI', {
  downloadFile: (buffer: any, filename: any) => {
    // 验证数据类型
    if (!(buffer instanceof Uint8Array)) {
      throw new Error('必须传递 Uint8Array 类型数据');
    }
    ipcRenderer.send('silent-download', { buffer, filename });
  },
  // 可选:接收主进程反馈
  onDownloadResult: (callback: (arg0: any) => void) => {
    ipcRenderer.on('download-result', (_event, result) => callback(result));
  }
});

electron-env.d.ts

javascript 复制代码
interface IElectronAPI {
  // 声明预加载脚本暴露的方法签名
  downloadFile: (buffer: any, filename: string) => void;
  onDownloadResult: (callback: (arg0: any) => void) => void
  // 其他方法...
}

// Used in Renderer process, expose in `preload.ts`
interface Window {
  ipcRenderer: import('electron').IpcRenderer,
  electronAPI: IElectronAPI;
}
相关推荐
正在走向自律5 分钟前
用豆包Seed Evolving打造全功能【AI智能记账】小程序,开源可落地
人工智能·小程序·开源·智能记账
To_OC8 小时前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
devlei9 小时前
Electron原理初探
electron
To_OC10 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
小林ixn10 小时前
从 ??= 到 onKeyDown:一个 React 组件的“自我修养”
前端·javascript·react.js
এ慕ོ冬℘゜11 小时前
前端实战:jQuery 多条件联合搜索(标题模糊查询 + 日历时间段筛选)
前端·javascript·jquery
随心点儿11 小时前
js postMessage 实现跨域发送消息-应用示例
javascript·ecmascript·postmessage
kyriewen13 小时前
我让AI改一个bug——它偷偷动了5个我没让它碰的地方
前端·javascript·ai编程
gis开发之家17 小时前
《Vue3 从入门到大神35篇》Vue3 源码详解(五):effect 依赖收集原理——track 与 trigger 是如何工作的?
javascript·typescript·前端框架·vue3·vue3源码
橘子星18 小时前
我一个前端切图仔,凭什么能在浏览器里跑大模型?
前端·javascript·前端框架