Announcement

Collapse
No announcement yet.

SocketTools SFTP Upload Example

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • SocketTools SFTP Upload Example

    There was a request for a simple example using SFTP to upload a file using SocketTools so I put one together. This uses the console compiler (6.04), but the same general principles would apply to the Windows compiler as well (we support both). This uses SocketTools 10 and the standard PB includes that we provide. It's a bit heavy on the comments, but general call flow isn't complex:

    1. FtpInitialize
    2. FtpConnect
    3. FtpChangeDirectory (optional)
    4. FtpGetFile (download) or FtpPutFile (upload)
    5. FtpDisconnect

    Here's a complete example. If you have any questions, I'll do my best to answer them here, or in private messages if you prefer.
    Code:
    '
    ' A simple console example to demonstratrate uploading a file to a
    ' server using SFTP with the SocketTools API. The same code could
    ' also be used for plain FTP and FTPS (FTP+TLS) by modifying the
    ' connection options.
    '
    #Compile Exe
    #Dim All
    
    ' Make sure that you have the path to the include file configured
    ' so that PowerBASIC can find the required files, for example:
    ' C:\Program Files (x86)\SocketTools 10.0 Library Edition\Include
    
    #Include "CSTOOLS10.INC"
    
    Function PBMain () As Long
    
        Dim hClient As Dword
        Dim szHostName As StringZ * 128
        Dim szUserName As StringZ * 128
        Dim szPassword As StringZ * 128
        Dim szLocalFile As StringZ * %Max_Path
        Dim szRemoteFile As StringZ * %Max_Path
        Dim nResult As Long
    
        ' Initialize the API, which validates your development runtime
        ' license key and loads the needed networking and other system
        ' libraries
    
        If FtpInitialize($CSTOOLS10_LICENSE_KEY, 0) = %FALSE Then
            PrintError("Unable to initialize SocketTools")
            End
        End If
    
        ' Define the name of the server you want to connect to, and the
        ' credentials for the user (username and password). This example
        ' connects using the default SSH port, but it's possible to
        ' specificy an alternate/non-standard port number if needed.
        '
    
        szHostName = "my.server.tld"
        szUserName = "userid"
        szPassword = "secret"
    
        hClient = FtpConnect(szHostName,    _ ' The server hostname or IP address
                             %FTP_PORT_SSH, _ ' The port number
                             szUserName,    _ ' The user name (user ID)
                             szPassword,    _ ' The user password
                             %FTP_TIMEOUT,  _ ' Timeout period in seconds, default is 20
                             %FTP_OPTION_SECURE_SHELL, _ ' The the API we're using SFTP
                             0)
    
        ' If the client handle is valid, then we have a connection to the
        ' server, otherwise something has gone wrong, so display the error
    
        If hClient = %INVALID_CLIENT Then
            PrintError("Unable to connect to " + szHostName)
            End
        End If
    
        Print "Connected to " + szHostName
    
        ' Specify the file names for the transfer. The local file is the
        ' one on the local system that we will be uploading. The remote
        ' file is the name of the file that should be created or replaced
        ' on the server.
        '
        ' Keep in mind that the remote file name can include a path, but
        ' that path should normally be relative, not absolute (i.e.: the
        ' path would typically not begin with a "/" character)
        '
        ' If you want change your current working directory on the server
        ' prior to uploading the file, you can do that using the
        ' FtpChangeDirectory function
    
        szLocalFile = "C:\Users\UserName\Documents\LocalFile.dat"
        szRemoteFile = "Files/Uploaded.dat"
    
        nResult = FtpPutFile(hClient,      _ ' The client session handle
                             szLocalFile,  _ ' The local file being uploaded
                             szRemoteFile, _ ' The file being created on the server
                             %FTP_TRANSFER_DEFAULT, _ ' Default transfer options
                             0)
    
        ' If nResult is %FTP_ERROR when FtpPutFile returns, then the
        ' upload has failed, display the error message
    
        If nResult = %FTP_ERROR Then
            PrintError("File upload failed")
            FtpDisconnect(hClient)
            End
        End If
    
        ' The transfer has completed successfully, we're all finished.
        ' Close the connection to the server and let the user know.
    
        FtpDisconnect(hClient)
    
        Print szLocalFile + " was uploaded successfully"
        Print "Press any key to continue ...";
        Con.WaitKey$
    
    End Function
    
    ' A helper function that uses the FtpGetLastError and FtpGetErrorString
    ' functions to display human-readable information about an error
    
    Sub PrintError(strMessage As String)
    
        Dim szError As StringZ * 128
        Dim dwError As Dword
    
        ' SocketTools returns error codes using the standard Win32 format
        ' composed of a facility code and error code; FtpGetLastError
        ' returns the last error code that was set for the current thread.
        '
        ' It is important to note that functions do not routinely clear
        ' the error code after every operation; like the Win32 SetLastError
        ' and GetLastError functions, the last error code is only changed
        ' when an error actually occurs.
        '
        ' This means that you should only call FtpGetLastError immediately
        ' after the previous function has returned a value which specifically
        ' indicates failure (e.g.: %INVALID_HANDLE, %FTP_ERROR, %FALSE, etc.)
    
        dwError = FtpGetLastError()
    
        If dwError = 0 Then
            szError = "No error"
        Else
            ' This performs a lookup for a human-readable string which
            ' describes the numeric error code. This makes it easier to display
            ' errors to a user, rather than a long hexadecimal number
            FtpGetErrorString(dwError, szError, 128)
        End If
    
        Print strMessage + "(" + szError + ")"
        Print "Press any key to continue ...";
    
        Con.WaitKey$
    End Sub
    Mike Stefanik
    sockettools.com

  • #2
    Thanks Mike
    I'm using PBwin 10 , do you have codes in PBWin as I'm ignorant about PB console compiler?

    where can I download $CSTOOLS10_LICENSE_KEY and CSTOOLS10.INC
    I would only need an evaluation license key to test out the program, you can PM me

    Comment


    • #3
      This same code would largely work the same for the Windows version, you'd just replace print statements with a message box. During the evaluation, there is no license key. Your test code will work on your development system (where SocketTools is installed), but you won't be able to redistribute it. The include file is installed as part of the Library Edition installation.

      The download form for the Library Edition can be found at https://sockettools.com/library-edition-download/

      Mike Stefanik
      sockettools.com

      Comment


      • #4
        I created a PBWin version (modified from another example), but since it's a bit more complicated and involves multiple files, I put it in a zip file that can be downloaded here. It's essentially the same thing, but it has all of the various Windows forms/controls scaffolding. It does show how you can hook up events to update a progress bar, if that's something you're interested in.
        Mike Stefanik
        sockettools.com

        Comment


        • #5
          Thank you Mike

          Comment

          Working...
          X