Electron 開啟儲存檔案對話方塊

Horizons-code發表於2020-12-12

1、引入相關模組

imports = {};
imports.fs = require('fs');  // nodejs檔案系統模組
imports.remote = require('electron').remote;
window.imports = imports;

2、主要程式碼

  onSaveButtonClick(): void {
    const dialog = this.imports.remote.dialog;
    const window = this.imports.remote.getCurrentWindow();

    let options = {
      title: "儲存檔案",
      defaultPath : "C:\\自定義檔名.txt",
      filters :[
        { name: 'Images', extensions: ['jpg', 'png', 'gif'] },
        { name: 'Movies', extensions: ['mkv', 'avi', 'mp4'] },
        { name: 'Custom File Type', extensions: ['as'] },
        { name: 'All Files', extensions: ['*'] }
      ]
    };

    dialog.showSaveDialog(window, options).then(result => {
      var stream = this.imports.fs.createWriteStream(result.filePath);
      if (this.windRainButtonType)
        this.createWindAndRainFile(stream);
      
      if (this.snowButtonType)
        this.createSnowFile(stream);
        
    }).catch(error => {
      console.log(error);
    });
  }

3、showSaveDialog方法引數二options屬性
title: 對話方塊視窗的標題。
defaultPath :對話方塊的預設展示路徑。
filters :對話方塊過濾檔案。

詳細介紹請參考:https://www.electronjs.org/docs/api/dialog

4、開啟的對話方塊
在這裡插入圖片描述

相關文章