vue2使用electron-builder打包-使用electron的api实现文件下载

本项目用的是vue2版本开发,最后使用electron-builder打包成桌面应用程序

一、需求描述

1、用户点击按钮,下载html文件

2、代码

复制代码
exportHtml() {
//.html是放在public文件夹下面的本地文件
      axios.get("/html/合同模板.html").then(res => {
        let a = document.createElement("a");
        let url = window.URL.createObjectURL(
          new Blob([res.data], {
            type: "text/html;charset='utf-8'" //这里指定的type对于桌面应用程序不生效,对浏览器有用
          })
        );
        a.href = url;
        a.download = "合同模板.html";
        a.click();
        window.URL.revokeObjectURL(url);
      });
    },
  • 浏览器下载

  • 桌面应用程序下载

    二、优化需求:保存类型为.html类型,弹窗的标题改为"另存为"

    大概思路介绍: 点击下载按钮时在vue页面使用dialog弹窗,自定义title和文件类型,保存时,在vue页面使用electronipcRenderer与主进程(background.js)通信,将下载文件的数据信息传过去,在主进程中保存文件。

1、 安装electron: npm install -s electron (本项目使用11的版本)"electron": "^11.5.0"

2、在background.js中配置

复制代码
 async function createWindow() {
  win = new BrowserWindow({
    width: 1200,
    height: 800,
    icon:path.join(__dirname,'favicon.ico'),
    webPreferences: {
      nodeIntegration:true,// process.env.ELECTRON_NODE_INTEGRATION,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
      enableRemoteModule:true  //启用Remote模块
    },
   
  })

3、vue中引入(main.js)

复制代码
//electron需要打开,如果只是单纯的运行vue项目浏览器会报错
const electron = window.require('electron')
const remote = window.require("electron").remote
Vue.prototype.$electron = electron
Vue.prototype.$remote = remote

4、在需要导出文件的.vue页面使用

复制代码
exportHtml() {
      axios.get("/html/合同模板.html").then(res => {
         let url = window.URL.createObjectURL(
          new Blob([res.data], {
            type: "text/html"
          })
        );
        //使用remote模块的dialog
       this.$remote.dialog.showSaveDialog(
        {
          title: "另存为",
          filters: [
            { name: ".html", extensions: [".html"] } //另存为的数据类型
          ],
          defaultPath: `${this.fileName}.html`  //这个是文件名称,后面必须要加上.html后缀
        }).then(res=>{
		  	//变量值
           const obj = {
            url: url,
            filePath: res.filePath 
           }
           this.$electron.ipcRenderer.send('sendFile',JSON.stringify(obj))  
         }).catch((err)=>{
          console.log("err",err)
        })
       
      });
    },

5、在background.js页面接收

复制代码
import {  ipcMain } from 'electron'
ipcMain.on('sendFile',(event,arg)=>{
  const data = JSON.parse(arg)
  if(data.filePath){
    win.webContents.downloadURL(data.url); 
  }
  win.webContents.session.once('will-download', (event, item, webContents) => {
    if (!data.filePath) return;
    //设置下载项的保存文件路径
    item.setSavePath(data.filePath);
	});
})
相关推荐
夏殇之殁8 小时前
包中创建自定义列表项。 . 使用自定义列表项进行数据绑定 . 将天气预报数据保存到本地内存表,通过LiveBindings进行显示。 ...
服务器·前端·javascript
新中地GIS开发老师9 小时前
WebGIS开发学生作品|低空航天管理与航线规划系统
前端·javascript·webgis·三维gis开发
丙氨酸長鏈9 小时前
Web前端入门第 问:JavaScript 一个简单的 IndexedDB 数据库入门示例
前端·javascript·数据库
kyriewen10 小时前
面试官让我手写虚拟列表——AI生成的版本,快速滚动几下就白屏了
前端·javascript·面试
林焱_RPAAI11 小时前
影刀RPA技术深度:CSS选择器高级实战指南——伪类属性选择器与性能对比完全解析
vue.js·react.js
许彰午13 小时前
政务督办的分合模式:主办协办的并发审批
前端·javascript·政务
陳陈陳13 小时前
🚀 前端流式输出革命:SSE + BFF 架构从零到一实战指南
vue.js·架构·node.js
易筋紫容13 小时前
创建型模式:对象的诞生艺术
开发语言·前端·javascript
0_Error_15 小时前
猫国建设者 修改资源 自动采集
javascript
贩卖黄昏的熊15 小时前
NestJS简明教程——安全
开发语言·javascript·安全·typescript·nest.js