B4A Library Automated FTP Library

New Automated FTP Library


UPDATED 3-24-2014 - Version 1.06 changes the display scale and should look better on the larger display of a tablet. A sample project is now included which shows how to use this library. The sample code requires B4A 3.2+. You can open and view the code with older versions but it will not run because of the newer layout files.


UPDATED 1-24-2014 - Version 1.05 adds a new function for checking for files or folders. It also contains a few other small fixes.
The new command works for Files or Folders. If the last parameter is set to TRUE, it will look for folders, if the last parameter is set to FALSE it will look for files. Because the code runs in the background and is modeless you must have a callback sub in the calling module. Code samples below:

B4X:
'Call the command like this:
FTP.FileOrFolderExist("plane.jpg" , "test/files", False)

B4X:
'Callback sub in calling module:
Sub FTP_FileExist(Found As Boolean)
    If Found Then Log("True") Else Log("False")
End Sub

UPDATED 4-2-2013 - Version 1.02 Corrects an issue where PassiveMode was not working and also corrects an issue where UploadFileSet would not work from File.DirInternal.

Automates the process of sending and receiving files using FTP with Wildcards & File Masks. Version 1.02 is attached. Please post/report back any issues you find, etc.

This library has progress bars for Each File and overall progress. It handles wildcards and multi file types at the same time. Issue one command and transfer multiple files and multiple types! Change the colors, text size and words of all objects on the Progress Dialog to fit the look of your app. Also works in Stealth Mode!

REQUIRES: B4A 2.5 +
Copy the FTP_Auto.jar & FTP_Auto.xml files to the Extra Libraries folder.


ss.png


FTP_Auto
  • Close
    Completes the current Que with any files left to process and then
    closes the connection.
  • CloseNow
    Closes the connection and all other files in the Que are
    ignored and the process is terminated.
  • DeleteFile (DeletePathAndFile As String)
    Deletes a single file from the server.
    Example:

    DeleteFile("public/pictures/airplane1.jpg")
  • DeleteFileSet (VerifyBeforeDelete As Boolean)
    Delete the lastest FileSet in memory from the server.
    If you used a Mask to download a set of files, this function
    will delelete all files in that last set.
    NOTICE: use with care.
  • DownLoadFile (LocalPath As String, ServerPath As String, FileName As String, Delete_FromServer As Boolean)
    Downloads a selected file from the FTP server and optionally deletes the file after successful download
    Example:

    DownLoadFile("/mnt/sdcard/pictures/", "public/downloads/", "airplane.jpg", False)
  • DownloadFileSet (LocalPath As String, Files_Path_And_Mask() As String, Delete_FromServer As Boolean)
    Retrieves a list of files from the server matching the Mask(s) passed to Files_Path_And_Mask() array.
    You should include the full server path in the Mask. It will then download these files to
    the Folder passed in LocalPath. Files_Path_And_Mask() can contain one entry or however many is needed.
    Example:

    DownloadFileSet(File.DirInternal, Array As String("SM*.txt", "public/pictures/pla*.jpg"), False)
  • IsInitialized As Boolean
    Tests whether the object has been initialized.
  • Initialize (Activity As Activity, CalledFrom As Object, FTP_Site As String, UserName As String, PassWord As String, PortNumber As Int, ShowMessages As Boolean, UsePassiveMode As Boolean) As String
    Initializes the object for use. If True is passed for ShowMessages, additional
    messages will be displayed throughout the process. Use the keywords "Activity"
    and "Me" For the first two parameters.
    Example:

    Initialize(Activity, Me, "ftp.yourdomain.com", "userName", "PassWord", "Port", True, False)
  • LastDownloadStats ( As ) As String
    Shows a popup window with the detials of the latest Download(s).
  • LastProcessSuccessful As Boolean
    Returns True if the last Upload or Download process was successful, otherwise returns False.
  • LastUploadStats ( As ) As String
    Show a popup window with details of the latest Upload(s).
  • MakeDir (DirectoryName As String)
    Makes a directory on the FTP server. Does nothing if the directory already exist.
    If you want to make a directory in the root of the server and then a directory under
    it, you must issue the command twice.
    Example:

    MakeDir("test")
    MakeDir("test/datafolder")
  • RemoveDir (DirectoryName As String)
    Removes selected directory from the FTP server
  • SetColors (HeadingColor As Int, TotalProgressColor As Int, FileTextColor As Int, PanelBackgroundColor As Int, FrameColor As Int)
    Used to set colors of each Item in the status dialog.
    NOTE: Passing 0 for any argument with leave that item unchanged
  • SetCompletedDownloadDialog (ShowCompletedDialog As Boolean, DialogText As String)
    If ShowCompletedDialog=True, it will show a dialog after the download process is completed.
  • SetCompletedUploadDialog (ShowCompletedDialog As Boolean, DialogText As String)
    If ShowCompletedDialog=True, it will show a dialog after the upload process is completed.
  • SetProcessCompleteOn (ProcessCompleteOn As Boolean)
    Use this function to determine by code when the Upload or Download is finished.
    The calling Activity must contain a sub named FTP_ProcessComplete. If your calling
    Activity includes this sub and you set this function to True, then the sub will
    be called as soon as the process has completed. EXAMPLE:

    'Add this sub to calling Activity
    Sub FTP_ProcessComplete
    'Your code here...
    End Sub
  • SetStealthOn (UseStealth As Boolean)
    If set to True, no progress box will be displayed during the file
    transfer. If False the progress dialog will show during the file
    transfers. The default is False.
  • SetStickyOn (MakeSticky As Boolean)
    If set to True, the progress box will stay on the screen until
    the user taps the Done button, otherwise the progress box will close
    as soon as the transfer is complete. The default is False.
  • SetText (HeaderDownLoadText As String, HeaderUploadText As String, TotalProgressText As String, FileProgressText As String, ButtonCancelText As String, ButtonDoneText As String)
    Used to set the Text of the Item's status display.
    NOTE: May be used for different language, etc.
  • SetTextSize (HeaderTextSize As Int, TotalProgressTextSize As Int, FileProgressTextSize As Int, CancelAndDoneTextSize As Int)
    Used to set the Text size of the Item's Text in the status dialog.
    NOTE: Passing 0 for any argument with leave that item unchanged
  • UpLoadFile (LocalPath As String, ServerPath As String, FileToSend As String)
    Uploads a single file passed in FileToSend

    Example: UpLoadFile("/mnt/sdcard/pictures", "uploads/pictures", "vacation.jpg")
  • UploadFileSet (ServerPath As String, Files_Path_And_Mask() As String, DeleteFileFromLocalDevice As Boolean)
    Retrieves a list of files from the local device. The Files_Path_And_Mask() array should contain the full
    path to the local devices files. It will then upload these files to the server.
    Files_Path_And_Mask() array can contain one entry or however many is needed.
    Example:

    UploadFileSet("uploads/pictures/", Array As String("/mnt/pictures/VA*.jpg", "/mnt/sdcard/backups/contact*.dat"), False)
  • WiFi_IsConnected As Boolean
    Check if Wifi is connected
    Returns True if connected otherwise returns False

Permissions:
◦android.permission.ACCESS_WIFI_STATE
◦android.permission.INTERNET
 

Attachments

  • Automated FTP Version 1.05.zip
    14.8 KB · Views: 968
  • Automated FTP Version 1.06.zip
    14.3 KB · Views: 1,609
  • FTP_Auto_Sample_Code_1.06.zip
    322.9 KB · Views: 1,770
Last edited:

Dataverde

Member
Licensed User
Longtime User
Hello,

is there a way to change the progress dialog?
Like, changing the color or size?
Also it would be nice if i could add an icon.

Keep up the good work :)
 

Dataverde

Member
Licensed User
Longtime User
Maybe i found an error or i am doing something wrong, see this:


This code:
B4X:
Sub ftpExport_click
   FTP.Initialize(Activity,all.ftpServer,all.ftpUsername,all.ftpPassword,all.ftpPort,True,False)
   FTP.SetColors(Colors.Black,Colors.Black,Colors.Black,Colors.Gray,Colors.DarkGray)
   If FTP.WiFi_IsConnected Then
      Try
         FTP.UploadFileSet(all.ftpTargetDir,Array As String(all.exportPath&"*.txt"))
         FTP.DownLoadFile(all.updatePath,all.ftpUpdateDir,"dataverde.sql",all.ftpDeleteAfterDownload)
      Catch
         Msgbox("Die Daten wurden nicht übertragen. Überprüfwn Sie die Verbindung.","Fehler")
         FTP.CloseNow
      End Try
   Else
      ToastMessageShow("Stellen Sie vorher eine Verbindung zum WLan her.",True)
      FTP.CloseNow
   End If
End Sub

Generates this log:
B4X:
Uploaded: //mnt/sdcard/dataverdeExport/test/260213_1352_Angebot.txt, Success=true...
Uploaded: //mnt/sdcard/dataverdeExport/test/260213_1345_Auftrag.txt, Success=true...
Uploaded: //mnt/sdcard/dataverdeExport/test/180213_1025_Auftrag.txt, Success=true...
Uploaded: //mnt/sdcard/dataverdeExport/test/180213_1024_Auftrag.txt, Success=true...
Uploaded: //mnt/sdcard/dataverdeExport/test/180213_0919_Auftrag.txt, Success=true...
Uploaded: //mnt/sdcard/dataverdeExport/test/310113_1457_Angebot.txt, Success=true...
Uploaded: //mnt/sdcard/dataverdeExport/test/310113_1043_Einkauf.txt, Success=true...
Uploaded: //mnt/sdcard/dataverdeExport/test/021012_1523_Auftrag_Meier.txt, Success=true...
Uploaded: //mnt/sdcard/dataverdeExport/test/021012_1454_Auftrag_aaa.txt, Success=true...
Uploaded: //mnt/sdcard/dataverdeExport/test/021012_1316_Auftrag_.txt, Success=true...
Uploaded: //mnt/sdcard/dataverdeExport/test/021012_1314_Angebot_Meier.txt, Success=true...
Uploaded: //mnt/sdcard/dataverdeExport/test/021012_1312_Einkauf_Helmers.txt, Success=true...
Uploaded: //mnt/sdcard/dataverdeExport/test/021012_1309_Einkauf_Lex.txt, Success=true...
Uploaded: //mnt/sdcard/dataverdeExport/test/021012_1306_Auftrag_Müller.txt, Success=true...


Without the "FTP.DownLoadFile" commad:
B4X:
Sub ftpExport_click
   FTP.Initialize(Activity,all.ftpServer,all.ftpUsername,all.ftpPassword,all.ftpPort,True,False)
   FTP.SetColors(Colors.Black,Colors.Black,Colors.Black,Colors.Gray,Colors.DarkGray)
   If FTP.WiFi_IsConnected Then
      Try
         FTP.UploadFileSet(all.ftpTargetDir,Array As String(all.exportPath&"*.txt"))
         'FTP.DownLoadFile(all.updatePath,all.ftpUpdateDir,"dataverde.sql",all.ftpDeleteAfterDownload)
      Catch
         Msgbox("Die Daten wurden nicht übertragen. Überprüfwn Sie die Verbindung.","Fehler")
         FTP.CloseNow
      End Try
   Else
      ToastMessageShow("Stellen Sie vorher eine Verbindung zum WLan her.",True)
      FTP.CloseNow
   End If
   'FTP.LastDownloadStats
   'FTP.LastUploadStats
End Sub


It generates this log:
B4X:
Uploaded: //mnt/sdcard/dataverdeExport/test/260213_1352_Angebot.txt, Success=true...
dataverde.sql
Uploaded: //mnt/sdcard/dataverdeExport/test/260213_1345_Auftrag.txt, Success=true...
Downloaded: //mnt/sdcard/dataverdeUpdates/dataverde.sql, Success=true
Uploaded: //mnt/sdcard/dataverdeUpdates/dataverde.sql180213_1025_Auftrag.txt, Success=true...

The files have not been changed or deleted between the tests.
It seems the FTP thing is stopping the upload queue when the download is finished? Also the log has confused/merged export(upload) and update(download) dirs in the last entry of the second log?
 

margret

Well-Known Member
Licensed User
Longtime User
You should never issue an Upload and a download command together. That will create a mess. Do each as a separate process.

Also, you should not issue the FTP.Close, the process runs in the background and your code will execute before the background code and it will terminate the process before it is completed. The Upload and Download both call the FTP.Close on their own once the process is complete. The only reason for you to call these functions is if you want to terminate the process early.

I thought most users would watch the progress dialog to see the status and completion of the job. It seems some are not doing this but wanting the code to do it for them. So, I am working on adding code feedback so that it can be used that way. This is one of the reasons I posted it as a Beta as it is hard to tell how each will use this.

For me it works fine because I use the visual feedback but I do understand the need for the code feedback and the issues one would run into trying to use it that way. I will post the New Update as soon as I have it ready.

Thanks
 

Dataverde

Member
Licensed User
Longtime User
First of all, thank you for the ongoing work you put in this! :icon_clap:


Okay, an upload and a download button it is then :)
I use the ftp.closeNow to hide the progress dialog when there is an error during file transfer.

The feedback for the user with the process dialog is just fine but please consider 2 things:

1. My customers are usually very unconfortable with PCs, it even gets worse on android devices. So for them i would like something like a "Everything went fine"-msgbox after the ftp transfer(or a "update is ready, apply now?" decision). They always get confused if a dialog simply disapears("did i do something wrong?" "no, its ok" "are you shure?").
To be more flexible it would be perfect if we could just handle the finished queue with an event.

2. Can we somehow customize the text that is displayed? My customers are german for example and it would be nice if i could change the text to fit their needs.
 

margret

Well-Known Member
Licensed User
Longtime User
New Beta Version .99 is now attached to post #1 of this thread. New features are listed below.

Updated 3-17-2013
NEW FEATURES ADDED TO BETA .99:

  • SetCompletedDownloadDialog (ShowCompletedDialog As Boolean, DialogText As String) As String
    If ShowCompletedDialog=True, it will show a dialog after the download process is completed.
  • SetCompletedUploadDialog (ShowCompletedDialog As Boolean, DialogText As String) As String
    If ShowCompletedDialog=True, it will show a dialog after the upload process is completed.
  • SetStealthOn (UseStealth As Boolean) As String
    If set to True, no progress box will be displayed during the file
    transfer. If False the progress dialog will show during the file
    transfers. The default is False.
  • SetStickyOn (MakeSticky As Boolean) As String
    If set to True, the progress box will stay on the screen until
    the user taps the Done button, otherwise the progress box will close
    as soon as the transfer is complete. The default is False.
  • SetText (HeaderDownLoadText As String, HeaderUploadText As String, TotalProgressText As String, FileProgressText As String, ButtonCancelText As String, ButtonDoneText As String) As String
    Used to set the Text of the Item's status display.
    NOTE: May be used for different language, etc.
 

Dataverde

Member
Licensed User
Longtime User
Hey,

tested the new features, they work fine.
There is a problem with the buttons textsize.
See the screenshot from the Nexus 7:

Te2brPfgGep7HSQFNZVpiGD4d92TOCh_Dg4BkV2Q2NE

dropbox link


I would like to disable the toasmessages the class is displaying.

Is there a way to know when the upload/download is finished?
I need that to move the uploaded files to an other folder.
 
Last edited:

Dataverde

Member
Licensed User
Longtime User
In the Initialize command, set ShowMessages to false to stop the messages.

The toastmessage "Reading local files information..." is still displayed somehow.

B4X:
   FTP.Initialize(Activity,all.ftpServer,all.ftpUsername,all.ftpPassword,all.ftpPort,False,False)
 

Dataverde

Member
Licensed User
Longtime User
You save me from doing all the FTP stuff my self, so i have to thank you ;-)
Looking forward to the next update.
 

cjolly

Member
Licensed User
Longtime User
Hi Margret,

I need you clarify how it works in Initialize "CalledFrom As Object".

The library is fantastic, thanks for simplify the work with ftp server :wav:

*TIA*
 

Dataverde

Member
Licensed User
Longtime User
Tested v1.0 today.

The FTP_ProcessComplete is working like a charm for me! Thanks.


Is there any way to know if the process of uploading or downloading was sucessfull?
 

margret

Well-Known Member
Licensed User
Longtime User
If it completes the process it was successful. If there are any errors, it will show a popup and abort the process. If this shows to be an issue, I may change the way this is coded. But again, if there is an error the process will stop and display an error message that you have to clear. So, if you do not have to clear an error message, all went well. Are you looking for something else?
 
Last edited:

cjolly

Member
Licensed User
Longtime User
Hi Margret,

For some reason I'm not getting that FTP_ProcessComplete work, could you post an "functional" example. :confused:

I'm using for development B4A and v2.52 Android SDK 4.2.2 - API 17 and test phone is a Samsung GT-S56500L with Android 2.3.6.

:sign0085: The code I'm using is:

Sub FTPUpload
FTP.Initialize (Activity, Me, "www.zzzzzz.com.py", "zzzzzz", "zzzzzz", 21, True, False)
FTP.SetText("BAJANDO DEL FTP", "SUBIENDO AL FTP", "procesados", "procesando", "CANCELAR", "CONCLUIDO")
FTP.UploadFileSet("/var/conf/ventas/files/", Array As String(File.DirRootExternal & "/ventas_log/*.zip"))
End Sub


Sub FTP_ProcessComplete
Log("datos enviados")
Dim borrar As String
LISTx.Initialize
LISTx = File.Listfiles(File.DirRootExternal & "/ventas_log/")
LISTx.SortCaseInsensitive(True)
For i = 0 To LISTx.Size -1
borrar = LISTx.Get(i)
If borrar.EndsWith(".zip") = True Then 'solo los zipeados
File.Delete(File.DirRootExternal & "/ventas_log/",LISTx.get(i))
Log("borrando " & File.DirRootExternal & "/ventas_log/" & " - " & LISTx.Get(i))
End If
Next
End Sub

*TIA*:(:(:(:(
 
Last edited:
Top