LoginSignup
2
8

More than 5 years have passed since last update.

ElectronからローカルファイルをSFTPでサーバーにアップロードする方法

Last updated at Posted at 2016-12-19

ElectronでSFTPを通じてファイルをアップロードしたい場合の方法です。

npmモジュールを追加します。

spawnとかつかってShellコマンドを操作するでもいいですが、簡単な方法としてはssh2モジュールがおすすめです。ただし、素のssh2だとリモート側でのmkdirが用意されていないようでしたので、今回はssh2のラッパーであるssh2-sftp-clientを使って、ディレクトリ作成を含んだSFTPアップロードの方法をご紹介します。

インストール

npm i ssh2-sftp-client --save

使い方

function upload () {
    let Client = require('ssh2-sftp-client');
    let sftp = new Client();

    var localPath = home + '/Gene/gene/themes/index.html';
    var remotePath = 'Your remote dir // e.g./home/user/www/dir/sample/';
    var remoteFilePath = remotePath + 'File name // e.g. index.html';

    sftp.connect({
        host: 'Your ftp host',
        port: 22, // Port
        username: 'Your user name',
        password: 'Your password'
    }).then(() => {
        return sftp.mkdir(remotePath, false);
    }).then(() => {
        return sftp.put(localPath,remoteFilePath, true);
    }).then((data) => {
        console.log("Success!!");
    }).catch((err) => {
        console.log(err, 'Error!!');
    });
}

以上です。

参考

npm - ssh2-sftp-client

2
8
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
2
8