electron 文件另存為需要用到的知識點(diǎn)有:
1.ipcMain(從主進(jìn)程到渲染進(jìn)程的異步通信)信不。
2.dialog(顯示用于打開和保存文件肿孵、警報(bào)等的本機(jī)系統(tǒng)對話框)。
3.ipcRenderer(從渲染器進(jìn)程到主進(jìn)程的異步通信) 。
4.類:downloadItem(控制來自于遠(yuǎn)程資源的文件下載)霜幼。
下面我們開始文件另存為的操作:
1镊讼、首先創(chuàng)建一個文件(download.js)用于文件的打開沛膳、保存 等功能的封裝稍坯,方便維護(hù)及管理。(這里只做了文件另存為)代碼如下:
const { ipcMain, dialog, shell } = require('electron')
const path = require('path')
const fs = require('fs')
exports.initDownload = function (win) {
let filePath = '';
// 監(jiān)聽渲染進(jìn)程發(fā)出的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、在主進(jìn)程中引入download中的 initDownload() 。并且在 let win = new BrowserWindow() 后調(diào)用該方法
3帝火、可以在寫一個插件 用于從渲染進(jìn)程發(fā)送消息到主進(jìn)程。名字隨意清酥。
import { ipcRenderer } from 'electron'
/**
* 文件下載
*/
export function download(path) {
ipcRenderer.send('download', path)
}
4、創(chuàng)建一個頁面蕴侣。在頁面引入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>
文件另存為到這里就結(jié)束了昆雀,如果還有什么不懂的可以去查看electron開發(fā)文檔