您的位置:首页 > 游戏 > 手游 > vue2使用electron-builder打包-使用electron的api实现文件下载

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

2024/9/24 19:20:10 来源:https://blog.csdn.net/qq_41713136/article/details/141559606  浏览:    关键词: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模块的dialogthis.$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);});
})

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com