1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Electronのdialogを使ってファイルピッカーを作る

Posted at

参考

dialog | Electron
続・Electronでファイルやフォルダの選択(保存もあるでよ)

はじめに

この記事ではElectronのdialogを使用して最小構成のファイルピッカーを作ります。
Electronを触り始めて2秒しかたっていない私にとってわかりやすい記事がなかったためメモ書き程度にまとめました。少しでも私と同じ境遇の人の助けになれば幸いです。
JavaScriptの"Hello Word"が読める人を対象にしています。

必要なもの

  • Electronの最小構成のアプリケーション
    この記事ではElectronの最小構成のアプリケーションを上書きする形でアプリを作っていきます。このサイトを参考に最小構成のアプリケーションを用意してください。

  • 空のスクリプト
    ファイル名はDialogSample.jsとしてください。このファイルにアプリのファイルピッカー部分を書き込んでいきます。

フォルダ構成

Sample
├─node_modules // Electronをインストールした際に作られる
│ ├.bin
│    ・
│    ・
│    ・
├─DialogSample.js // 空のスクリプト
├─index.html
├─main.js
├─package.json
└─package-lock.json // Electronをインストールした際に作られる

アプリのイメージ

今回は下の画像のようなアプリを作ります。ボタンを押すとファイルピッカーが起動し、ファイルを選択するとConsoleに選択したファイルへのパスが出力されるようにします。
キャプチャ.PNG

ソースコード

index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>dialog sample</title>
</head>

<body>
  <button id="open-file-button">open file</button>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
  <script src="./DialogSample.js"></script>
</body>
</html>
DialogSample.js
const remote = require('electron').remote;
const Dialog = remote.dialog;

$(function(){
  $('#open-file-button').on('click', function(){
    Dialog.showOpenDialog(null, {
    }, (fileNames) => {
      console.log(fileNames);
    });
  });
});

出力結果

キャプチャ3.PNG

おまけ オプションについて

もう少しカスタマイズされたファイルピッカーが作りたいという方にオプションが用意されています。下のように記述することができます。詳しくはこちらに書かれているので参考にしてください。

Dialog.showOpenDialog(null, {
  // ここにオプションを書く
  title: 'title',
  defaultPath: 'C:\\ ',
  buttonLabel: 'buttonLabel',
  filters: [
    {name: 'HTML', extensions: ['html']},
    {name: 'JavaScript', extensions: ['js']},
    {name: 'All', extensions: ['*']}
  ],
  properties: ['openFile']
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?