美文网首页
electron 文件另存为

electron 文件另存为

作者: 白衣诗人 | 来源:发表于2023-02-23 12:01 被阅读0次

electron 文件另存为需要用到的知识点有:
1.ipcMain(从主进程到渲染进程的异步通信)。
2.dialog(显示用于打开和保存文件、警报等的本机系统对话框)。
3.ipcRenderer(从渲染器进程到主进程的异步通信) 。
4.类:downloadItem(控制来自于远程资源的文件下载)。
下面我们开始文件另存为的操作:
1、首先创建一个文件(download.js)用于文件的打开、保存 等功能的封装,方便维护及管理。(这里只做了文件另存为)代码如下:

const { ipcMain, dialog, shell } = require('electron')
const path = require('path')
const fs = require('fs')
exports.initDownload = function (win) {
    let filePath = '';
    // 监听渲染进程发出的download事件
    const webContents = win.webContents;
    ipcMain.on('download', (evt, args) => {
        const fileArr = args.split("/");
        let ext = path.extname(args)
        let filters = [{ name: '全部文件', extensions: ['*'] }]
        if (ext && ext !== '.') {
          filters.unshift({
            name: '',
            extensions: [ext.match(/[a-zA-Z]+$/)[0]]
          })
        }
        dialog.showSaveDialog(win, {
            filters,
            defaultPath:args
        }).then( res => {
            if(res.filePath){
                filePath = res.filePath
                webContents.downloadURL(args) // 注意这里必须是下载文件可访问路径。而不是存储路径
            }
        })
    })
    webContents.session.on('will-download', (event, item, webContents) => {
        item.setSavePath(filePath) // 这里是存储路径或者存储文件名称
        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}`)
            }
        })
    })
}

需要注意的是win.webContents.downloadURL(path)。path是可访问的文件路径。
2、在主进程中引入download中的 initDownload() 。并且在 let win = new BrowserWindow() 后调用该方法
3、可以在写一个插件 用于从渲染进程发送消息到主进程。名字随意。

import { ipcRenderer } from 'electron'

/**
 * 文件下载
 */
export function download(path) {
    ipcRenderer.send('download', path)
}

4、创建一个页面。在页面引入download()方法,这里以vue为例。

<template>
  <div class="home">
        <button @click="down">文件下载</button>
  </div>
</template>

<script>
    import {download} from '@/plugins'
export default {
    name: 'HomeView',
    data() {
        return {
        }
    },
    methods:{
        down:function(){
               download("https://fanyiapp.cdn.bcebos.com/cms/image/88083c3025affd20e87d3a575f6bcb68.jpg")
        }
    }
}
</script>

文件另存为到这里就结束了,如果还有什么不懂的可以去查看electron开发文档

相关文章

网友评论

      本文标题:electron 文件另存为

      本文链接:https://www.haomeiwen.com/subject/wngzkdtx.html