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: 998
  • Automated FTP Version 1.06.zip
    14.3 KB · Views: 1,637
  • FTP_Auto_Sample_Code_1.06.zip
    322.9 KB · Views: 1,793
Last edited:

Smee

Well-Known Member
Licensed User
Longtime User
When using the library, just before the files are downloaded as wildcard entries, a listing of the files appears in the debug window. Is there a command to access this listing so that files within the list may be downloaded?

Thanks again
 

margret

Well-Known Member
Licensed User
Longtime User
That list is the list of files that will be downloaded. It is produced from the Masks you enter. So, I am not sure what you mean when you say you want to access this list to download files because that is the list of files that is being downloaded. Please try to explain in more detail so I know what you want to do. I am sure it can be added.

When using the library, just before the files are downloaded as wildcard entries, a listing of the files appears in the debug window. Is there a command to access this listing so that files within the list may be downloaded?

Thanks again
 

Smee

Well-Known Member
Licensed User
Longtime User
If for example i want all the .txt files in a directory, i will use the mask "*.txt" which lists all the txt files in the debug window and then downloads them.

So if i want all the files that have been added since a certain date or with a particular characteristic i could get a list of those files with and then in my software i could apply a filter to the list of names and then feed these names back to a download loop.

For ex

listing=FTP.List "*.txt"
for x=0 to listing.size-1
if listing(x) = specification then add to files to be downloaded
next

I hope this makes sense!
 
Last edited:

silz

New Member
Licensed User
Longtime User
Great job!:sign0098:

But how can I check if the login was corret established (invalid user/password etc.)?
And how you handle timeouts?

Sorry, about my English

Thanks
 
Last edited:

Rusty

Well-Known Member
Licensed User
Longtime User
I have used your sample code to create a test for your new library.
I'm having bad results
B4X:
Sub Process_Globals
End Sub

Sub Globals
    Dim FTP As FTP_Auto
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("Main")
    FTP.Initialize(Activity, Me, "www.xxx.com", "iii","ppp", 21, True, False)
End Sub

Sub Download_Click
If FTP.WiFi_IsConnected Then
        FTP.SetProcessCompleteOn(True)
        FTP.SetCompletedDownloadDialog(True,"Download succesful")
        FTP.DownLoadFile(File.DirRootExternal, "/directoryname", "filename", False)
    Else
        Msgbox("Message......","Error")
    End If
End Sub
Sub FTP_ProcessComplete
    If FTP.WiFi_IsConnected Then
        FTP.SetStealthOn(True)
    End If
End Sub
Sub Activity_Resume
End Sub
Sub Activity_Pause (UserClosed As Boolean)
End Sub
I've captured the unfiltered logs and:
B4X:
Start proc b4a.example for activity b4a.example/.main: pid=25299 uid=10047 gids={1015, 3003, 3002, 3001}
adjustConfigurationLw, config:{1.0 0mcc0mnc (no locale) layoutdir=0 sw800dp w1280dp h752dp xlrg land ?uimode ?night finger -keyb/v/h -nav/v} mLidOpen:-1 mHasDockFeature:true mHasHallSensorFeature:true config.hardKeyboardHidden:2
Flushing caches (mode 0)
Flushing caches (mode 1)
loaded /system/lib/egl/libEGL_tegra.so
Flushing caches (mode 0)
loaded /system/lib/egl/libGLESv1_CM_tegra.so
loaded /system/lib/egl/libGLESv2_tegra.so
Enabling debug mode 0
TextType = 0x0
Displayed b4a.example/.main: +532ms
** Activity (main) Create, isFirst = true **
GC_FOR_ALLOC freed 142K, 4% free 6747K/6983K, paused 15ms
** Activity (main) Resume **
Flushing caches (mode 0)
Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@4164c5f0
No longer want com.android.packageinstaller (pid 25259): hidden #16
WIN DEATH: Window{416ccfe0 com.android.packageinstaller/com.android.packageinstaller.InstallAppProgress paused=false}
[B][COLOR=Red]void cb_onMotion(uint16_t)[/COLOR][/B]
GC_FOR_ALLOC freed 33K, 4% free 7103K/7367K, paused 13ms
Grow heap (frag case) to 7.330MB for 358416-byte allocation
GC_FOR_ALLOC freed <1K, 4% free 7453K/7751K, paused 13ms
No longer want com.android.keychain (pid 25278): hidden #16
GC_CONCURRENT freed 404K, 14% free 7186K/8327K, paused 6ms+2ms
void cb_onMotion(uint16_t)
Activity destroy timeout for ActivityRecord{4136d1b0 com.android.packageinstaller/.InstallAppProgress}
Triggered Alarm 413aeee8 RTC_WAKEUP IntentSender{417c14c0: PendingIntentRecord{41649520 com.android.vending startService}}
GC_CONCURRENT freed 534K, 8% free 7530K/8135K, paused 3ms+2ms
[1] 5.onFinished: Installation state replication succeeded.
Nothing happens. The red line in the logs is where I touch the download button. The blue "downloading" box appears with total progress words but no progress is indicated, nor is the file downloaded.
Any suggestions/advice will be greatly appreciated.
Regards,
Rusty

P.S. the red highlight didn't work, the line in the log is void cb onMotion(uint16 t)
 
Last edited:

Smee

Well-Known Member
Licensed User
Longtime User
This line looks like an error

FTP.DownLoadFile(File.DirRootExternal, "/directoryname", "filename", False)

unless the file you are trying to download is called filename.

if it is a variable it should not be enclosed in quotes otherwise it should be somefilename.txt or somefilename.jpg or similar
 

Rusty

Well-Known Member
Licensed User
Longtime User
No, it was illustrative.
I took out my passwords, id's, website, folder, filename for privacy.
Can you seen anything else wrong with it?
It looks pretty clear to me, but it isn't working.
Nor is the FTP lib, the NET lib or any other FTP lib I've tried...
It used to work...
Thanks,
Rusty
 

Smee

Well-Known Member
Licensed User
Longtime User
No,Other than the quotes around the word filename the code is the same as i use

if other libs are not working then i would suspect something else is at play
 

upsis

Member
Licensed User
Longtime User
File exists in server

HI Margret, How do I know if a file exists in server before I send download command?
Thanks in advance
 

margret

Well-Known Member
Licensed User
Longtime User
At this point you do not but there is a way! You can use the DownloadFileSet function, it pulls a list of files matching the Mask into an array. It then downloads this array so there is no error if a file is not there.

Again, this array list is built from the files it finds on the server matching the Mask. You can then check the download path and see if the file you are looking for is there.

NOTE: This array is not currently exposed to the programmer, but I may add this. I am looking into a few request that others have made and if I do them, I will add a function for this as well.
 

Smee

Well-Known Member
Licensed User
Longtime User
.NOTE: This array is not currently exposed to the programmer, but I may add this. I am looking into a few request that others have made and if I do them, I will add a function for this as well.

+1 for this Margret. Also would be good to expose the file time/date in the array

Thanks for the great library
 

afagcaoili

Member
Licensed User
Longtime User
Features/Function throughput

At this point you do not but there is a way! You can use the DownloadFileSet function, it pulls a list of files matching the Mask into an array. It then downloads this array so there is no error if a file is not there.

Again, this array list is built from the files it finds on the server matching the Mask. You can then check the download path and see if the file you are looking for is there.

NOTE: This array is not currently exposed to the programmer, but I may add this. I am looking into a few request that others have made and if I do them, I will add a function for this as well.

Hi,

Thanks for the library! Can you add the feature/function that gets the throughput? like file size/time and show it in the screen as well or ability to record it either in sqllite or text file?

Also, can we have a basic sample app with this? Maybe I missed it but I have been looking for the sample application. The newbie like us sometimes need that little catalyst to get us started and please forgive us.

Thanks a lot again!
 

afagcaoili

Member
Licensed User
Longtime User
At this point you do not but there is a way! You can use the DownloadFileSet function, it pulls a list of files matching the Mask into an array. It then downloads this array so there is no error if a file is not there.

Again, this array list is built from the files it finds on the server matching the Mask. You can then check the download path and see if the file you are looking for is there.

NOTE: This array is not currently exposed to the programmer, but I may add this. I am looking into a few request that others have made and if I do them, I will add a function for this as well.


This would be good to get all the files from the mask and also be able to get the file size of each and add it in the array.

Thanks.
 

afagcaoili

Member
Licensed User
Longtime User
Progress Dialog size

Hi,

It looks like we can modify the text sizes. Can we modify the Progress dialog size as well?

Thanks.

Arnold
 

CidTek

Active Member
Licensed User
Longtime User
Any chance of a nice clean looking toast-shaped (with rounded corners) progress bar? No frame or background - just the progress with perhaps the percentage as text centered in it. I'll add an image to this post when I get back to my main computer.

ProgressBar widget

The above link shows something close to what I had in mind although I think its best if the percentage was within the bar itself. I'm sure it could be repurposed for other projects as well.

Or even something simpler like...

aspnet-progress-bar-progress-indicator-key-features-image.jpg


but not green lol.
 
Last edited:

Dman

Active Member
Licensed User
Longtime User
This is great. It works fine in my project but after I download files, I want to delete all of the files in the folder on of the server. I see this but am unsure on what to here. I know that I need to put this in the FTP_ProcessComplete sub but I am confused on the parameter.

DeleteFileSet (VerifyBeforeDelete As Boolean)

Any examples?
 

rpina

Member
Licensed User
Longtime User
Message when deleting file

Hi Margret,
I'm wondering if there is a way to avoid notice message at the end of deleting a file on server

Kind Regard

Riccardo
 
Top