Back to Examples

SFTP service - Receive file

The ftp:Service connects to a given SFTP server via the ftp:Listener. A ftp:Listener with SFTP protocol is created by providing the protocol, host-name, required credentials, and the private key. Once connected, service starts receiving events every time a file is deleted or added to the server. To take action for these events ftp:Caller is used. The ftp:Caller can be specified as a parameter of onFileChange remote method. The ftp:Caller allows interacting with the server via get, append, delete, etc remote methods. Use this to listen to file changes occurring in a remote file system and take action for those changes.

import ballerina/ftp;
import ballerina/io;

// Creates the listener with the connection parameters and the protocol-related
// configuration. The listener listens to the files
// with the given file name pattern located in the specified path.
listener ftp:Listener fileListener = new ({
    protocol: ftp:SFTP,
    host: "sftp.example.com",
    auth: {
        credentials: {
            username: "user1",
            password: "pass456"
        },
        privateKey: {
            path: "../resource/path/to/private.key",
            password: "keyPass123"
        }
    },
    port: 22,
    path: "/home/in",
    fileNamePattern: "(.*).txt"
});

// One or many services can listen to the SFTP listener for the
// periodically-polled file related events.
service on fileListener {

    // When a file event is successfully received, the `onFileChange` method is called.
    remote function onFileChange(ftp:WatchEvent & readonly event, ftp:Caller caller) returns error? {
        // `addedFiles` contains the paths of the newly-added files/directories
        // after the last polling was called.
        foreach ftp:FileInfo addedFile in event.addedFiles {
            // Get the newly added file from the SFTP server as a `byte[]` stream.
            stream<byte[] & readonly, io:Error?> fileStream = check caller->get(addedFile.pathDecoded);

            // Write the content to a file.
            check io:fileWriteBlocksFromStream(string `./local/${addedFile.name}`, fileStream);
            check fileStream.close();
        }
    }
}

Prerequisites

Run the program by executing the following command. Each newly added file in the SFTP server will be saved in the local file system.

$ bal run sftp_service_read.bal

Tip: Run the SFTP client given in the SFTP client - Send file example to put a file in the SFTP server.

Related links

PreviousSend file
NextSend file