Jump to content
Elia

FTP Multiple Files with the same FTP Session

Recommended Posts

Elia

Hi All,

I am trying to write a script that FTPs multiple files to the same destination using the same FTP session. The script takes the source files, places them on the FTP server, the files should be FTP'd and then moved into the SENT folder in the original location.  I seem to have got everything working except when i try to FTP multiple files, if i put a specific file name under $LocalFile & $RemoteFile under FTP_FilePut then the script works, can anyone tell me where I am going wrong please? I've visited other forums and input an array for the $LocalFile which seems to work, as if i put an ArrayDisplay in it does show me all the files in the folder. I have tried to enter a path, "". '' and "*.*" for $RemoteFile but nothing seems to work:

#include <FTPEx.au3>
#include <MsgBoxConstants.au3>
#include <WinAPIFiles.au3>
#include <Inet.au3>
#include <Debug.au3>
#include <File.au3>
#include <Array.au3>

Local $Server = 'ftp.com'
Local $Username = 'user'
Local $Password = 'password'
Local $LocalFile = 'C:\FTP\doc.txt'
Local $RemoteFile = '*.*'
Local $FilePath = 'C:\FTP'

FileMove ("\\COMP\Source\*.txt", "\\COMP\FTP")

If FileExists ( "\\COMP\FTP" ) Then
    Local $FileList = _FileListToArray($FilePath, "*", 1)
    Local $Open = _FTP_Open('FTP Test')
    Local $Connect = _FTP_Connect($Open, $Server, $Username, $Password)
    If $Connect <> 0 Then
        For $i = 1 to $FileList[0] - 1
            Local $Transfer = _FTP_FilePut($Connect, $FileList[$i], "" ,0 ,0)             <------------- I think the problem is with the $RemoteFile part
        Next
            _FTP_Close($Connect)
            _FTP_Close($Open)
        
            FileMove ( "\\COMP\FTP\*.txt", "\\COMP\Source\SENT")
     EndIf
EndIf

Share this post


Link to post
Share on other sites
Jos

What was the idea behind opening 3 threads on the same topic in different forums?

mmm.. and one more just popped up. Next one will urn you a posting holiday from our forums!

Jos

Edited by Jos

Visit the SciTE4AutoIt3 Download page for the latest versions  - Beta files                                How to post scriptsource        Forum Rules
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Share this post


Link to post
Share on other sites
AutoBert

Yes the problem is the remotepath it mustn't be blank. Here a small script i wrote in 2011:

;https://autoit.de/index.php/Thread/14918-Deutsche-Hilfe-Funktionen-ohne-Beispiel/?postID=214046#post214046#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_AU3Check_Parameters=-d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#include <FTPEx.au3>
#include <File.au3>
#include <Array.au3>

Opt('MustDeclareVars', 1)

_example2()

Func _example2()
    ;lädt alle Dateien eines Ordner mithilfe  _FTP_FilePut auf den FTP-Server (noch ohne Unterordner)
    Local $s_ServerName = 'guest.autobert.myplace.net'  ;dieser Server existiert nicht
    Local $s_Username = "guest"
    Local $s_Password = "TopSecret"

    Local $s_LocalFolder = @ScriptDir ;das angegebene Verzsichnis muss existieren
    Local $s_RemoteFolder = "/FTPTestfiles/Test/" ;dieser Ordner wird notfalls angelegt
    Local $i_Passive = 0 ;manche Server benötigen hier eine 1 für Passiven Modus
    Local $l_InternetSession, $l_FTPSession, $errOpen, $errFTP

    $l_InternetSession = _FTP_Open('AuoItZilla') ;Öffnet eine FTP Sitzung
    $errOpen = @error
    If Not @error Then
        $l_FTPSession = _FTP_Connect($l_InternetSession, $s_ServerName, $s_Username, $s_Password, $i_Passive) ;Verbindet zu einem FTP Server
        $errFTP = @error
        If Not @error Then
            _FolderPut($l_FTPSession, $s_LocalFolder, $s_RemoteFolder, "_FTP*3.au3") ;kopiert alle au3 Dateien
            If Not @error Then
                ConsoleWrite("_FolderPut: " & @extended & " Dateien erfolgreich übertragen" & @CRLF)
            Else
                ConsoleWrite("_FolderPut Fehler:" & @error & " " & @extended & @CRLF)
            EndIf
        Else
            MsgBox(0, "Connect", "fehlgeschlagen")
            ConsoleWrite("Connect: " & " " & $errFTP & @CRLF)
        EndIf
    Else
        MsgBox(0, "Open", "fehlgeschlagen")
        ConsoleWrite("Open " & " " & $errOpen & @CRLF)
    EndIf
    _FTP_Close($l_InternetSession) ;schliesst die Sitzung
EndFunc   ;==>_example2

Func _FolderPut($l_FTPSession, $s_LocalFolder, $s_RemoteFolder, $sFilter = "*")
    Local $bDebugFP = True ;um Debuginfos an- auszuschalten
    If $bDebugFP Then ConsoleWrite("Lokal " & $s_LocalFolder & " Remote " & $s_RemoteFolder & @CRLF)
    if StringRight($s_RemoteFolder,1) <> "/" Then $s_RemoteFolder &= "/"
    if StringLeft($s_RemoteFolder,1) <> "/" Then $s_RemoteFolder = "/" & $s_RemoteFolder
    Local $aPathSplit = StringSplit($s_RemoteFolder, "/")
    _ArrayDisplay($aPathSplit)
    For $i = 2 To $aPathSplit[0] -1     ;Element 1 ist leer ebenso letztes durch StringTrim.....
        If $bDebugFP Then ConsoleWrite($aPathSplit[$i])
        _FTP_DirSetCurrent($l_FTPSession, $aPathSplit[$i])
        If @error Then
            If $bDebugFP Then ConsoleWrite(@TAB & "wird versucht anzulegen" & @TAB)
            _FTP_DirCreate($l_FTPSession, $aPathSplit[$i])
            _FTP_DirSetCurrent($l_FTPSession, $aPathSplit[$i])
            If @error Then
                If $bDebugFP Then ConsoleWrite("Fehler " & @error & @CRLF)
                SetError(1, $i)
                Return 0
            Else
                If $bDebugFP Then ConsoleWrite("OK" & @crlf)
            EndIf
        Else
            If $bDebugFP Then ConsoleWrite("/")
        EndIf
    Next
    If $bDebugFP Then ConsoleWrite(@CRLF & "Aktuelles Verzeichnis" & _FTP_DirGetCurrent($l_FTPSession) & @CRLF)
    Local $aUpload_Files = _FileListToArray($s_LocalFolder, $sFilter, 1)
    Local $iErrors = 0
    Local $iSuccess = 0
    For $i = 1 To $aUpload_Files[0]
        If $bDebugFP Then ConsoleWrite($aUpload_Files[$i] & @TAB)
        If _FTP_FilePut($l_FTPSession, $aUpload_Files[$i], $aUpload_Files[$i]) Then
            $iSuccess +=1
            If $bDebugFP Then ConsoleWrite("OK" & @CRLF)
        Else
            $iErrors += 1
            If $bDebugFP Then ConsoleWrite("Fehler: " & @error & @CRLF)
        EndIf
    Next
    if $iErrors > 0 Then
        SetError(2, $iErrors, 0)
    Else
        SetExtended($iSuccess)
    EndIf
EndFunc   ;==>_FolderPut

Note: the func _FolderPut is non recursiv.

  • Like 1

Share this post


Link to post
Share on other sites
Elia

Hi AutoBert,

Thank you so much! I have changed from using an _FTP_FilePut command to _FTP_DirPutContents, this means I was also able to remove the array as it was no longer needed. For anyone else this is now the working code:

#include <FTPEx.au3>
#include <MsgBoxConstants.au3>
#include <WinAPIFiles.au3>
#include <Inet.au3>
#include <Debug.au3>
#include <File.au3>
#include <Array.au3>

Local $Server = 'ftp.com'
Local $Username = 'user'
Local $Password = 'password'
Local $LocalFolder = 'C:\FTP'
Local $RemoteFolder = '/users/FTP'

FileMove ("\\COMP\Source\*.txt", "\\COMP\FTP")

If FileExists ( "\\COMP\FTP" ) Then
    Local $Open = _FTP_Open('FTP Test')
    Local $Connect = _FTP_Connect($Open, $Server, $Username, $Password)
    If $Connect <> 0 Then
            Local $Transfer = _FTP_DirPutContents($Connect, $LocalFolder, $RemoteFolder, 0)    <-------------- New line
            _FTP_Close($Connect)
            _FTP_Close($Open)
            FileMove ( "\\COMP\FTP\*.txt", "\\COMP\Source\SENT")
     EndIf
EndIf

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • Sally1801
      By Sally1801
      Hello,
      i need help in deleting files from a server. The function "_FTP_DirDelete" only deletes a directory when its empty. I need to delete a non empty directory. I also can not delete the files in this directory first, because the files are PAG and DIR files in a .DAV directory and FTPEx.au3 doesnt like a directory starting with a ".".
      Any ideas?
      Thx, Sally
    • CharlieH
      By CharlieH
      Hi,
       
      I have written a small script to read a file from an FTP server and check its contents. This can be re-run by the press of a button, however, if the file is deleted from the ftp server between runs (with the .exe still live), the file is still "read" and written locally, which then passes the check.
       
      If I run it initially without the file, it correctly fails and pops up my error message, but if the file is then added, it then seemingly gets cached (or similar) so that the app then always reports a success.
       
      The below code snippet is just the function run when the "test" button is pressed. It includes a load of debug message boxes, and from that I think I've gathered a few (possibly) interesting/relevant things:
      $Open and $Conn are 8 byte values, which increments (not by 1) when the FTP connection is not closed, but if the connection is closed, they stick at the value (presumably windows can re-use that session id if it's been closed e.g:
      1st run (file not present) $Open -> 0x00CC0004 $Conn -> 0x00CC0008
      2nd run (file not present) $Open -> 0x00CC0010 $Conn -> 0x00CC0014
      3rd run (file now present) $Open -> 0x00CC001C $Conn -> 0x00CC0020
      4th run (file still present) $Open -> 0x00CC001C $Conn -> 0x00CC0020
      $Ftp = _FTP_FileGet.... returns a 1 when file not present (in a run after it was present) and "test_transfer.txt" does get created and does contain the correct string This is the key bit I dont understand, I dont know how/where it is getting the data to write this file when it literally no longer exists on the target FTP server...
      resetting every variable used in the function each time it's run does work (in that they become 0), but it doesn't affect the putcome I had thought perhaps some key values were being stored in the variables, but this doesn't seem to be the case
       
       
      Is there any concept of clearing a cache when closing an ftp session? Or deleting any unknown temporary files windows might make?
       
      Thanks all
       
      Func Transfer() Local $connected = 0 $Ftpp = 0 ;Trying to reset these every time function is called $file = 0 $Open = 0 $Conn = 0 $Ftpc = 0 ;Make a new "connecting..." window so that the user has feedback that a transfer is attempting to take place ;Otherwise it just runs in the background and there's no indication its doing anything $connection_window = GUICreate ("Ethernet Switch Test" , 300 , 160 , -1 , -1 , -1 , -1 , 0) GUISetBkColor(0xFFFFFF) GUISetFont(10 * _GDIPlus_GraphicsGetDPIRatio()[0], 400, Default, "Sans Serif") $connecting_label = GUICtrlCreateLabel("Connecting to board...", 0, 25, 300, -1, $SS_Center, "") GUISetState(@SW_SHOW, $connection_window) Sleep(100) ;Connect ;MsgBox(0, "DEBUG", "1" & $Conn) While $connected = 0 $Open = _FTP_Open($count) ;MsgBox(0, "DEBUG", "open " & $Open) $Conn = _FTP_Connect($Open, $server, $username, $password) ;MsgBox(0, "DEBUG", "2" & $Conn) If $Conn = 0 then Local $retry = Msgbox(65, 'FTP Transfer', 'Connection failed' & @CRLF & "Retry?") If $retry = 2 Then MsgBox(0, "FTP Transfer", "Operation aborted") GUISetState(@SW_HIDE, $connection_window) Return EndIf Else $connected_label = GUICtrlCreateLabel("Connected!", 0, 45, 300, -1, $SS_Center, "") $connected = 1 MsgBox(0, "DEBUG", "3" & $connected) Sleep(100) endIf WEnd $transfering_label = GUICtrlCreateLabel("Reading file....", 0, 45, 300, -1, $SS_Center, "") ;Read file from server ;MsgBox(0, "DEBUG", "5" & $Ftpp) ;MsgBox(0, "DEBUG", "flie " & $file) $Ftpp = _FTP_FileGet($Conn, 'test/test.txt', 'test_transfer.txt') ;MsgBox(0, "DEBUG", "6" & $Ftpp) If ($Ftpp) then $transfered_label = GUICtrlCreateLabel("Transfered, checking...", 0, 65, 300, -1, $SS_Center, "") ;MsgBox(0, "DEBUG", "flie " & $file) $file = FileRead("test_transfer.txt") ;MsgBox(0, "DEBUG", "flie " & $file) If Not StringInStr($file, 'this is a test string 12345') Then MsgBox(0, "File check", "Received file incorrect, test failed!") GUISetState(@SW_HIDE, $connection_window) Return Else $tested_label = GUICtrlCreateLabel("Tested and Passed!", 0, 85, 300, -1, $SS_Center, "") $Ftpc = _FTP_Close($Open) ;MsgBox(0, "DEBUG", "close" & $Ftpc) ;$count = $count+1 $ok_button = GUICtrlCreateButton("OK", 125, 105, 50, -1) While 1 Local $pressed = GUIGetMsg() If ($pressed = $ok_button) Then FileDelete("test_transfer.txt") GUISetState(@SW_HIDE, $connection_window) ;$connection_window = 0 Return EndIf WEnd EndIf Else MsgBox(0, "Transfer", "Could not read file " & @error) GUISetState(@SW_HIDE, $connection_window) Return EndIf EndFunc  
    • Sigmac
      By Sigmac
      I have used this code for a long time, but for a week or 2 it stopped working?
      Connection is ok, the put create the file on server if I delete it on the FTP server, but the file is empty and after 30 secondees the function return 0
      I have tested on 2 machines, Filezilla FTP client have no issue to the server.
      Firewall is disabled under test.
        If $writeFTP = True Then
            $Open=_FTPOpen('MyFTP Control')
            $Conn=_FTPConnect($Open, $destinationServer, $destinationUsername, $destinationPass)
       MsgBox(0,"start","start")
            $Ftpp=_FtpPutFile($Conn, $filePath&$name&".json", "httpdocs/p_calender/" & $name & ".json")
      MsgBox(0,"return","return"&$Ftpp)
      Exit
            $Ftpc=_FTPClose($Open)
           EndIf
       
      From the Lib:
      Func _FTPPutFile($l_FTPSession, $s_LocalFile, $s_RemoteFile, $l_Flags = 0, $l_Context = 0)
          Local $ai_FTPPutFile = DllCall('wininet.dll', 'int', 'FtpPutFile', 'long', $l_FTPSession, 'str', $s_LocalFile, 'str', $s_RemoteFile, 'long', $l_Flags, 'long', $l_Context)
          If @error OR $ai_FTPPutFile[0] = 0 Then
              SetError(-1)
              Return 0
          EndIf
          Return $ai_FTPPutFile[0]
      EndFunc ;==> _FTPPutFile()
       
    • mLipok
      By mLipok
      As for now I was using such kind of snippet:
      Local $aFTP_FileList = _FTP_ListToArray($hFTPSession, 2) For $iFTPFileSize_idx = 1 To $aFTP_FileList[0] ConsoleWrite('Pobieram informacje o pliku:' & $aFTP_FileList[$iFTPFileSize_idx] ) $iWielkoscPliku = _FTP_FileGetSize($hFTPSession, $aFTP_FileList[$iFTPFileSize_idx]) ConsoleWrite($iFTPFileSize_idx & ' : ' & $aFTP_FileList[$iFTPFileSize_idx] & ' rozmiar=' & $iWielkoscPliku) Sleep(200) Next  
      But from some time my clients start buying cheap WD MyCloud NAS, and my problems starts.
      On all others NAS there is no problem (Seagate BlackArmour, QNAP, SYNOLOGY .... ).

      When on list there is for example 20 files then first two of them are very fast checked and reported they FileSize.
      After 2 files there is about 20 sec stop....... and next two files are checked with no errors but FileSize == 0 
      again there is about 20 sec stop....... and next two files are checked with no errors but FileSize == 0 
      again there is about 20 sec stop....... and next two files are checked with no errors but FileSize == 0 
      again there is about 20 sec stop....... and next two files are checked with no errors but FileSize == 0 
      again there is about 20 sec stop....... and next two files are checked with no errors but FileSize == 0 
      .......
       
      In time when I process investigation I checked how :  _FTP_ListToArray2D and _FTP_ListToArrayEx works and I was shocked that they works super fast.
       
      Here are the questions:
      Q1: Why does the problem occur only on WD MyCloud NAS?
      Q2: What is the significant difference that makes using _FTP_ListToArray2D and _FTP_ListToArrayEx to retrieve file sizes is still fast?
      Q3: Why _FTP_FileGetSize() not reporting @errors but returned FileSize = 0 
       
      Regards,
      mLipok
       
    • mLipok
      By mLipok
      In documentation for:
       
      #include <FTPEx.au3> _FTP_Connect ( $hInternetSession, $sServerName, $sUsername, $sPassword [, $iPassive = 0 [, $iServerPort = 0 [, $iService = $INTERNET_SERVICE_FTP [, $iFlags = 0 [, $fuContext = 0]]]]] ) There are two parameters for Passive:
       
      My question is: 

      What is a difference beetwen  using :
      $iPassive = 1
      and
      $iFlags =     $INTERNET_FLAG_PASSIVE
      Regards,
      mLipok
       
×