Discuss this help topic in SecureBlackbox Forum

SFTP: Upload file

There exist several ways to upload the file to the remote server.

First way is to use UploadStream() or UploadFile() method of TElSimpleSFTPClient class to upload a single data block which makes a file. UploadStream() method accepts a reference to the data stream (be it file stream, or memory stream, or BLOB stream or some other stream). UploadFile() method accepts the absolute path (with a file name) of the local file. Another parameter for the above mentioned methods is the absolute path to the remote file (SFTP doesn't have a concept of "current directory") to which the data will be uploaded/writen.

A simple call to UploadFile() would look like:


	TElSimpleSFTPClient c = new TElSimpleSFTPClient();
	c.Address = "domain.com";
	MemoryStream ms = new MemoryStream();
	c.DownloadStream(@"/remote/file.dat", ms);
	ms.Position = 0; // reset position in the stream to be able to read the data from it.

If you have more than one file to upload, you can use UploadFiles() method of TElSimpleSFTPClient class. This method accepts the local folder, the standard file mask for local files or the regular expression and the absolute path to the remote directory (SFTP doesn't have a concept of "current directory"), where the files will be placed. The method lets you perform case conversion of the file names during file upload.

Both UploadStream(), UploadFile() and UploadFiles() have TransferMode parameter, which specifies the way how the component behaves when the remote file with the specified name exists. Possible options are

  1. skip the existing file
  2. append the data to the end of the remote file
  3. resume the transfer, if the size of the remote data is less than size of the local file
  4. overwrite the data
  5. transfer the data to the file with a new name
  6. rename the existing destination, then transfer the file.

The application is notified about the progress of the single file upload operation using OnProgress event of TElSimpleSFTPClient class. UploadFiles() also notifies the application, when the next file is to be processed, using OnFileOperation() event of TElSimpleSFTPClient class. Using both events you can cancel the upload operation.

The most sophisticated and flexible way is to use OpenFile/Write/ CloseHandle sequence of methods. Use OpenFile() or CreateFile() method of TElSimpleSFTPClient class to open or create the file and get a file handle. The next step is to use Write() method to transfer the data. Don't pass the whole data block to this method. Use chunks which are smaller than 1 Mb. When you finish writing the data, use CloseHandle() method to close the file.

All of the above methods are synchronous and return when the operation is completed.

For information about error handling, see the corresponding how-to article.

How To articles about SFTP client

Discuss this help topic in SecureBlackbox Forum