Android Tutorial Android FTP tutorial

Status
Not open for further replies.
Old and irrelevant tutorial. Follow this one instead: [B4X] Net library (FTP, SMTP, POP) with Wait For

This tutorial covers the FTP object which is part of the Net library.
The Net library is based on Apache Commons Net.

Android OS doesn't allow us, the developers, to block the main thread for more than 5 seconds. When the main thread is busy for too long and is not able to handle the user events the "Application not responding" dialog appears.
Therefore slow operations like network operations should be done in the background.
The FTP library is built in such a way. All of the methods return immediately. When a task completes an event is raised. In fact you can submit several tasks one after another. The FTP protocol supports a single task at a time so the tasks will be processed serially.

Using the FTP library is pretty simple.
The first step is to initialize the FTP object. If this is an Activity module then you should do it in Activity_Create when FirstTime is true.
For Service modules it should be initialized in Service_Create.
B4X:
Sub Process_Globals
    Dim FTP As FTP
End Sub
Sub Globals

End Sub

Sub Activity_Create(FirstTime As Boolean)
    If FirstTime Then
        FTP.Initialize("FTP", "ftp.example.com", 21, "user", "password")
    End If
FTP.Initialize doesn't connect to the server. Connection will be established implicitly together with the next task.

Download

Downloading a file is done by calling DownloadFile with the remote file path and the local file path.
If you want to show the download progress then you should handle DownloadProgress event.
When download completes the DownloadCompleted event is raised. The ServerPath is passed as the first parameter to all events. You can use it to distinguish between different tasks. Make sure to check the Success parameter. If Success is False then you can find the exception message by calling LastException.

B4X:
    FTP.DownloadFile("/somefolder/files/1.zip", False, File.DirRootExternal, "1.zip")
   
Sub FTP_DownloadProgress (ServerPath As String, TotalDownloaded As Long, Total As Long)
    Dim s As String
    s = "Downloaded " & Round(TotalDownloaded / 1000) & "KB"
    If Total > 0 Then s = s & " out of " & Round(Total / 1000) & "KB"
    Log(s)
End Sub

Sub FTP_DownloadCompleted (ServerPath As String, Success As Boolean)
    Log(ServerPath & ", Success=" & Success)
    If Success = False Then Log(LastException.Message)
End Sub
Upload

Uploading is similar to downloading.
B4X:
    FTP.UploadFile(File.DirRootExternal, "1.txt", True, "/somefolder/files/1.txt")

Sub FTP_UploadProgress (ServerPath As String, TotalUploaded As Long, Total As Long)
    Dim s As String
    s = "Uploaded " & Round(TotalUploaded / 1000) & "KB"
    If Total > 0 Then s = s & " out of " & Round(Total / 1000) & "KB"
    Log(s)
End Sub

Sub FTP_UploadCompleted (ServerPath As String, Success As Boolean)
    Log(ServerPath & ", Success=" & Success)
    If Success = False Then Log(LastException.Message)
End Sub
List files and folders

FTP.List sends a request for the list of files and folders in a specific path.
The ListCompleted event is raised when the data is available.
You can use code similar to the following code to get more information on the entries:
B4X:
FTP.List("/")
...
Sub FTP_ListCompleted (ServerPath As String, Success As Boolean, Folders() As FTPEntry, Files() As FTPEntry)
    Log(ServerPath)
    If Success = False Then
        Log(LastException)
    Else
        For i = 0 To Folders.Length - 1
            Log(Folders(i).Name)
        Next
        For i = 0 To Files.Length - 1
            Log(Files(i).Name & ", " & Files(i).Size & ", " & DateTime.Date(Files(i).Timestamp))
        Next
    End If
End Sub
Delete
Delete is done by calling FTP.Delete with the full path. Again an event will be raised when the task completes (DeleteCompleted).

Closing the connection
You can close the connection by calling FTP.Close. Close will wait for the other tasks to complete and then will close the connection. This happens in the background.
FTP.CloseNow will immediately close the connection, failing the remaining tasks.

Some notes:
- At any given time there should be less than 15 waiting tasks. Otherwise you will get a RejectedExecutionException (this happens when the internal threads pool is exhausted).
- The order of the completed tasks may be different than the order of submission.
- The AsciiFile parameters sets the file transfer mode. If AsciiFile is true then every occurrence of an end of line character will be translated based on the server native end of line character. If your FTP server is Unix or Linux then the end of line character is the same as Android.
In most cases you can set AsciiFile to false.

The library is available for download here: http://www.basic4ppc.com/forum/addi...92-new-net-library-android-ftp-smtp-pop3.html
 
Last edited:

DonManfred

Expert
Licensed User

arnold steger

Member
Licensed User
i cannot see any download-command in your code
during the test of download i have insert in this methode.
B4X:
For i = 0To Files.Length - 1
Log(Files(i).Name & ", " & Files(i).Size & ", " & DateTime.Date(Files(i).Timestamp))
FTP.DownloadFile("Namen/", True, PfadDownload,name)
Next
 

LucaMs

Expert
Licensed User
1 min to check the event name: it is [YouEventName]_DownloadCompleted, where YouEventName is the name you set when you initialized FTP.

You should verify the ftp server path.

Note that this your code:
B4X:
For i = 0To Files.Length - 1
Log(Files(i).Name & ", " & Files(i).Size & ", " & DateTime.Date(Files(i).Timestamp))
FTP.DownloadFile("Namen/", True, PfadDownload,name)
Next

saves only one file, if you don't change the value of the variable [name] inside the For loop (name & i, for
 
Last edited:

arnold steger

Member
Licensed User
i have tested the upload file by file, total 7files
whit explore i have open the files directly from ftp server path for check data in files, work fine
i whant download all files from my server path (folder:Namen/)
on my device path maked 7 empty files whit the correct name from server

message #240
 

arnold steger

Member
Licensed User
Full path to the filename are my problem.
This code work fine, thanks.

B4X:
Sub ButtonDownloadList_Click
    Dim FolderName As String    :FolderName="Namen/"

    FTP.List(FolderName)

End Sub

Sub FTP_ListCompleted (ServerPath As String, Success As Boolean, Folders() As FTPEntry, Files() As FTPEntry)
    Dim FolderName As String    :FolderName="Namen/"

    Log(ServerPath)
    If Success = False Then
        Log(LastException)
    Else
    TimerDownload.Initialize("TimerDownload",3000)
    TimerDownload.Enabled=True

        For i = 0 To Folders.Length - 1
            Log(Folders(i).Name)
        Next     
        For i = 0 To Files.Length - 1
            Log(Files(i).Name & ", " & Files(i).Size & ", " & DateTime.Date(Files(i).Timestamp))
            FTP.DownloadFile(FolderName&Files(i).Name,True, PfadDownload,Files(i).Name)
            ToastMessageShow(Files(i).Name&" wird geladen...",False)
        Next
    End If
 
    If Success AND Files.Length>0 Then
    TimerDownload.Enabled=False
    ToastMessageShow(Files.Length&" Dateien wurden erfolgreich geladen",True)
    Else
    TimerDownload.Enabled=False
    ToastMessageShow(ServerPath&" Dateien konnten nicht geladen werden",True)
    End If
 
End Sub

Sub TimerDownload_tick
    ToastMessageShow("wird geladen..." ,False)
   
End Sub
 
Last edited:

arnold steger

Member
Licensed User
When use my code #257 then show afer 1 second "33 Dateien wurden erfolgreich geladen".
When checked in device folder after 30 second is all of list in my device.
How can check when all of files from my list is downloaded?
 

Julian Rogers

New Member
Licensed User
If a file already exists in your local folder, (ie, downloading "test.txt" onto a directory that already has a "test.txt"), what will happen? Will it delete the old file and replace with the new one? Will it rename anything?
 

arnold steger

Member
Licensed User
i have insert this code. not work.
how can tested if download of list is compled?

B4X:
If Success Then
ServerGeladen=ServerGeladen+1
End if   
If Success AND ServerGeladen>=Files.Length Then
    ToastMessageShow(Files.Length&" Dateien wurden erfolgreich geladen",True)
    TimerDownload.Enabled=False
End if
 

JAVIERGARCIA

Member
Licensed User
Hi Erel,
please look:
attempt to rename a file in a ftp upload, so:

FTP.UploadFile(File.DirRootExternal, "1.jpg", True, "/public_html/FOTOS-NGI/ '" & IDNUM & "' & ".jpg" ")

which it is a variable IDNUM
but I missed his syntax, it does not know why

and if you only put him
FTP.UploadFile(File.DirRootExternal, "1.jpg", True, "/public_html/FOTOS-NGI/ '" & IDNUM & "'")
FTP is correct, but when trying to access the file, tells me "invalid image"
I do not understand where failure

another thing,

Sub FTP_UploadProgress (ServerPath As String, TotalUploaded As Long, Total As Long)
Dim s As String
s = "Uploaded " & Round(TotalUploaded / 3000) & "KB"
If Total > 0 Then s = s & " out of " & Round(Total / 3000) & "KB"
Log(s)
End Sub

3000 is the most you might go up via ftp?

thanks
best regard
 

JAVIERGARCIA

Member
Licensed User
Hello,
if I make a ftp upload image when trying to open it once downloaded, always she tells me that the image is not valid,
why?


thanks
 

Kwame Twum

Active Member
Licensed User
Hello,
if I make a ftp upload image when trying to open it once downloaded, always she tells me that the image is not valid,
why?

1. Does the DownloadComplete Sub get raised?
2. Can you post the code you used in downloading the image? - It's possible you're downloading a file with no extension (from the look of the Post#257)
 

juventino883

Member
Licensed User
Hi!, I have a doubt, is possible to create a new folder in the FTP server through this library?, and how can i do it?, thanks!!!
 
Status
Not open for further replies.
Top