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:

hibrid0

Active Member
Licensed User
Longtime User
Hi I test your library and work so good on Wifi and I try with 3G/4G and show this error.

ERROR Uploading/
libcore.io.Errno.Exception:
recvfrom failed: ECONNRESET
(Connection reset by peer)

Over wifi work perfect.
 

hibrid0

Active Member
Licensed User
Longtime User
Hi I test your library and work so good on Wifi and I try with 3G/4G and show this error.

ERROR Uploading/
libcore.io.Errno.Exception:
recvfrom failed: ECONNRESET
(Connection reset by peer)

Over wifi work perfect.
Problem solved to upload files.
Solution:

Set to pasive mode true in the initialized.
 

Julian Rogers

New Member
Licensed User
Longtime User
Is there anything that I can use that is similar to the _Download/UploadComplete event handler? For instance, I am downloading a file that will be used to fill in data for a table and I want to only start filling in data once the file has successfully downloaded.
 

Alisson

Active Member
Licensed User
Margret, how catch the files path: /storage/emulated/0/Download/ and send to server?

I have the error in the app: An error has occurred in sub:main_v6 (java line: 371)
java.io.FileNotFoundException:/data/adr.ftp_auto.sample/filescropped-modal-in.jpg/sample1.jpg:ENOENT(No such file or directory)

Why have the error?
 

Alisson

Active Member
Licensed User
This path is my smartphone.
The code:


#Region Module Attributes
#FullScreen: True
#IncludeTitle: False
#ApplicationLabel: FTP Auto Sample
#VersionCode: 1
#VersionName: 1.0.1
#SupportedOrientations: landscape
#CanInstallToExternalStorage: False
#End Region

'APP Name: FTP Auto Sample
'Last Mod: March 24th, 2014
'Written By: Margret
'Location: Home System
'Version: For Library Version - 1.06
'Created In: B4A Version 3.2

#Region Activity Variables
Sub Process_Globals
End Sub
Sub Globals
Dim FTP As FTP_Auto
FTP.Initialize(Activity, Me, "ftp.domain.com", "username", "password", 21, False, False)

'Just used for the Layout*********************
Private Pmain, p1 As Panel '*
Private b1, b2, b3, b4, fset As Button '*
Private l1 As Label '*
Dim FTPSet, Pmain As Panel '*
Private mmap As Map : mmap.Initialize '*
Private ETdomain, ETuser, ETpass As EditText'*
'*********************************************
End Sub
#End Region

#Region Activity Create, Resume, etc.
Sub Activity_Create(FirstTime As Boolean)
SetDisplay
AddMenuItems
End Sub
Sub Activity_Resume
DoFTPInitialize
If Not(FTP.WiFi_IsConnected) Then
Msgbox("WiFi Is Off. Turn WiFi On And Restart App.", "NOTICE")
Activity.Finish
End If
File.MakeDir(File.DirInternal, "downloads")
End Sub
Sub Activity_KeyPress(KeyCode As Int) As Boolean
If KeyCode = KeyCodes.KEYCODE_BACK Then
Activity.Finish 'Exit Program
End If
End Sub
#End Region

#Region Set The Display & Menu Items
Sub SetDisplay
Activity.LoadLayout("acti")
Pmain.Width = Activity.Width
Pmain.Height = Activity.Height
l1.Width = Activity.Width
p1.Width = Activity.Width
Dim wherew As Int = (Activity.Width/2) - (b1.Width/2)
Dim wherev As Int = ((Activity.Height-40)/4) - (b1.Height/2)
b1.Left = wherew
b2.Left = wherew
b3.Left = wherew
b4.Left = wherew
b1.Top = wherev *1
b2.Top = wherev *2
b3.Top = wherev *3
b4.Top = wherev *4
End Sub
Sub AddMenuItems
File.MakeDir(File.DirInternal, "storage/emulated/0/Download")
File.Copy(File.DirAssets, "cropped-modal-min.jpg", File.DirInternal & "/storage/emulated/0/Download", "sample1.jpg")
File.Copy(File.DirAssets, "sample2.jpg", File.DirInternal & "/storage/emulated/0/Download", "sample2.jpg")
File.Copy(File.DirAssets, "sample3.jpg", File.DirInternal & "/storage/emulated/0/Download", "sample3.jpg")
Activity.AddMenuItem("Server Setup", "ServerSet")
Activity.AddMenuItem("Change Color", "CC")
Activity.AddMenuItem("Stealth On", "Stealth")
Activity.AddMenuItem("Sticky On", "Sticky")
Activity.AddMenuItem("Change Text Size", "ChangeTextSize")
Activity.AddMenuItem("Change Text", "ChangeText")
Activity.AddMenuItem("Set Progress Complete", "SetProgressOn")
Activity.AddMenuItem("Show Dialogs", "SetStealthDialogs")
End Sub
#End Region

#Region Buttons Click & Callback Events
Sub FTP_ProcessComplete
'If you use: FTP.SetProcessCompleteOn(True), this sub will be called after the last
'process completes.
Msgbox("Process Complete...", "NOTICE")
End Sub
Sub b1_Click 'Upload a single file, create folder first if it does not exist.
Log("Sending File...")
FTP.MakeDir("ftpsample")
FTP.UpLoadFile(File.DirAssets, "ftpsample", "ftpsample.jpg")
End Sub
Sub b2_Click 'Download a single file.
Log("Downloading File...")
'This command will call FTP_FileExist when finished.
FTP.FileOrFolderExist("ftpsample.jpg" , "ftpsample" , False)
End Sub
Sub FTP_FileExist(Found As Boolean)
'If you use: FTP.FileOrFolderExist(), this sub will be called as the process
'completes. Be sure to include this sub.
If Found Then
FTP.DownLoadFile(File.DirInternal & "/storage/emulated/0/Download", "ftpsample", "ftpsample.jpg", False)
Else
Msgbox("No Such File Found...", "NOTICE")
End If
End Sub
Sub b3_Click 'Uploads a file set with a wildcard, creates the folder if it does not exist.
Log("Sending File Set...")
FTP.MakeDir("ftpsample")
Dim SendFiles As String = File.DirInternal & "/storage/emulated/0/Download/*.jpg"
Log(SendFiles)
FTP.UploadFileSet("ftpsample", Array As String(SendFiles), False)
End Sub
Sub b4_Click 'Downloads a file set with a wildcard.
Log("Downloading File Set...")
Dim GetFiles As String = "ftpsample/*.jpg"
FTP.DownloadFileSet(File.DirInternal & "/storage/emulated/0/Download", Array As String(GetFiles), False)
End Sub
#End Region

#Region Change FTP Settings
Sub DoFTPInitialize
If File.Exists(File.DirInternal, "ftpsettings.map") Then
mmap = File.ReadMap(File.DirInternal, "ftpsettings.map")
FTP.Initialize(Activity, Me, mmap.Get("domain"), mmap.Get("user"), mmap.Get("pass"), 21, False, False)
Else
ChangeFTP
End If
End Sub
Sub ChangeFTP
FTPSet.Initialize("FTPSet")
Activity.AddView(FTPSet, 0, 0, Activity.Width, Activity.Height)
FTPSet.LoadLayout("ftpset")
Pmain.Left = Activity.Width/2 - Pmain.Width/2
Pmain.Top = Activity.Height/2 - Pmain.Height/2
If File.Exists(File.DirInternal, "ftpsettings.map") Then
mmap = File.ReadMap(File.DirInternal, "ftpsettings.map")
ETdomain.Text = mmap.Get("domain")
ETuser.Text = mmap.Get("user")
ETpass.Text = mmap.Get("pass")
End If
End Sub
Sub fset_Click
FTPSet.RemoveView
mmap.Put("domain", ETdomain.TexT)
mmap.Put("user", ETuser.TexT)
mmap.Put("pass", ETpass.TexT)
File.WriteMap(File.DirInternal, "ftpsettings.map", mmap)
DoFTPInitialize
End Sub
Sub ServerSet_Click
ChangeFTP
End Sub
Sub CC_Click
'Allows you to change the colors to anything you wish.
FTP.SetColors(Colors.White, Colors.White, Colors.White, Colors.Black, Colors.White)
End Sub
Sub Stealth_Click
'This causes the FTP dialog to not show and stay hidden. You can set: FTP.SetProcessCompleteOn(True)
'to call a sub when completed. See SetProgressOn_Click below. If you don't set
'FTP.SetProcessCompleteOn(True), there will be no indication if the process is complete
'or is still working.
FTP.SetStealthOn(True)
End Sub
Sub Sticky_Click
'This causes the FTP dialog to stay on the screen after the process, until the done button
'is clicked.
FTP.SetStickyOn(True)
End Sub
Sub ChangeTextSize_Click
'Changes the text size that the dialog displays.
FTP.SetTextSize(12,10,10,12)
End Sub
Sub ChangeText_Click
'This changes the text to what you want on the FTP dialog
FTP.SetText("Getting Files...", "Sending Files...", "Overall", "Each File", "Abort", "Finished")
End Sub
Sub SetProgressOn_Click
'This set to true will call a sub named: FTP_ProcessComplete if you have added it, when
'the process called completes it's task.
FTP.SetProcessCompleteOn(True)
End Sub
Sub SetStealthDialogs_Click
FTP.SetStealthOn(True)
FTP.SetCompletedDownloadDialog(True, "Update is Available")
FTP.SetCompletedUploadDialog(True, "All Files Transfered To Server")
End Sub
#End Region
 

hibrid0

Active Member
Licensed User
Longtime User
I see a problem in the patch. Your are using File.DirInternal and that point to internal site where is to save private data, then
Use:
B4X:
FTP.DownLoadFile(File.DirRootExternall & "/storage/emulated/0/Download", "ftpsample", "ftpsample.jpg", False)

Maybe There is your problem.
file.DirInternal="/data/data/com.yourapp.com/files"

Check by yourself where is that patch with:
B4X:
log("::Curren Patch::"&File.DirInternal & "/storage/emulated/0/Download")
 
Last edited:

ewing001

New Member
Licensed User
Longtime User
Hello

Why is not working this:
FTPA.UpLoadFile(Valtozok.DBFileDir, cursor3.getstring("ftpkonyv").Trim, fajlnev&".fel")
FTPA.SendCMD("RNTO ",fajlnev&".zip")
FTPA.SendCMD("RNFR ",&fajlnev&".fel")

Log is:
Uploaded: /00365520160214220250.fel, Success=true...
RNFR
false
0
 

ewing001

New Member
Licensed User
Longtime User
Sorry, misspelled

This:
FTPA.UpLoadFile(Valtozok.DBFileDir, cursor3.getstring("ftpkonyv").Trim, fajlnev&".fel")
FTPA.SendCMD("RNFR ",fajlnev&".fel")
FTPA.SendCMD("RNTO ",fajlnev&".zip")

Log is:
Uploaded: /00365520160214220250.fel, Success=true...
RNFR
false
0
 

MarianoD

Member
Licensed User
Longtime User
Margret, it is possible that when phone lock screen while uploading several files, it stoped sending? I selected 4 images files, then start uploading, because i dont tocuh my phone it block and screen go off, after 1 minute, when i unblock phone, the uploading dialog was stoped in image 3, ith progress bar not finished, and dont continue anymore, i have to close app. Do you know what can be? Some bug, some programming error, o maybe just a bad internet connection? Thanks ans apologize my english...
 

peacemaker

Expert
Licensed User
Longtime User
FTP_AUTO is Activity object :-(
Impossible to use in a service.
Why ?
 

luciano deri

Active Member
Licensed User
Longtime User
what sub is called when FTP_DownloadFileSet not find any files and show the message "No Files Found.."?
 
Top