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.b4x.com/forum/additional...92-new-net-library-android-ftp-smtp-pop3.html
 
Last edited:

DonManfred

Expert
Licensed User
Longtime User
ftpcmd0065.png
 

mojako

Member
Licensed User
If you are on a hosting web server you might not get
a file directory listing with this command:

FTP.List("/")


You should try using this instead:


FTP.List("./")


Worked for me, to get a directory listing for my home directory...
Yes, FTP.List("./") worked for me. The List is coming out.
but when I call ftp.UploadFile(File.DirDefaultExternal & "/", File.DirDefaultExternal & "/" & zipedfile, False, "./public_html/")
the log is : libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
what did I miss?
 

DonManfred

Expert
Licensed User
Longtime User
but when I call ftp.UploadFile(File.DirDefaultExternal & "/", File.DirDefaultExternal & "/" & zipedfile, False, "./public_html/")
The path is the path
your filename is a path and filename. Both together is a incorrect path-filename combination!

Go again over the ftp-tutorial (example) and find out what you did wrong
 

Valeriy Lakhtin

Member
Licensed User
Please help me DonManfred!
I have an FTP server, and from browser I can opens files and I can copie files to PC.
But I can not be copied to the phone all the files from a folder on my FTP. The error does not occur but there is no result. I have not found an example of how to get a list of files on FTP and then how to download all files from this list. I guess I'm not doing what that important action

B4X:
   ibFTP.Initialize("eventFTP", "ftp://ftp.informbyuro.kz", 21, "#####", "#####")
    yes=ibFTP.IsInitialized
    If yes=True Then
        Log("Hellow FTP!") ' this line OK
    End If

    Try
'    I want to download all the files from folders /ClikLike/Files but do not know. So I try to download one file, but there is no result
'    ibFTP.List("/")
    
    ibFTP.DownloadFile("/ClikLike/Files/g_zub.png", False, File.DirRootExternal, "/clicklike/Update/g_zub.png")

    Catch
    Log(LastException.Message)
    End Try
 
Last edited:

DonManfred

Expert
Licensed User
Longtime User
Please help me DonManfred!
This is a community forum. Don´t limit your question to a single member!

So I try to download one file, but there is no result
you need to wait to the
B4X:
FTP_DownloadCompleted
event is raised...

Same principle for the List command... here you get the
B4X:
FTP_ListCompleted (ServerPath As String, Success As Boolean, Folders() As FTPEntry, Files() As FTPEntry)
event.

Go over the ftp documentation and the ftp-tutorial again i suggest
 

Valeriy Lakhtin

Member
Licensed User
I understand your point "This is a community forum. Don´t limit your question to a single member!"
So be sure to use
FTP_DownloadCompleted
And need wait when this event is raised then file downloaded. I checked on my the phone the file is very small and it is downloaded for 1-2 seconds
 

Valeriy Lakhtin

Member
Licensed User
I'm happy all worked aftere I changed the address.
"ftp://ftp.informbyuro.kz" to
"ftp.informbyuro.kz"


the following question, before downloading the need to clean the place or will rewrite files
 

rtek1000

Active Member
Licensed User
Longtime User
Hi,

The FTP server received a corrupted file

Is FTP only for text files?

I tried uploading it with another FTP client app downloaded in the play store and it worked correctly

Log:
Uploaded 1KB
Uploaded 2KB
Uploaded 3KB
Uploaded 4KB
Uploaded 5KB
Uploaded 6KB
Uploaded 7KB
Uploaded 8KB
Uploaded 9KB
Uploaded 10KB
Uploaded 11KB
Uploaded 12KB
Uploaded 13KB
Uploaded 14KB
Uploaded 15KB
Uploaded 16KB
Uploaded 17KB
Uploaded 18KB
Uploaded 19KB
Uploaded 20KB
Uploaded 22KB
Uploaded 23KB
Uploaded 24KB
Uploaded 25KB
Uploaded 26KB
Uploaded 27KB
Uploaded 28KB
Uploaded 29KB
Uploaded 30KB
Uploaded 31KB
Uploaded 32KB
Uploaded 33KB
Uploaded 34KB
Uploaded 35KB
Uploaded 36KB
/sdcard/1.wav, Success=true

B4X:
FTP.UploadFile(File.DirRootExternal & "/TTS2File/", filename, True, "/sdcard/" & filename)
B4X:
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
 

Attachments

  • Audio wav.zip
    61.8 KB · Views: 526

rtek1000

Active Member
Licensed User
Longtime User
Hi,

The FTP server received a corrupted file

Is FTP only for text files?

I tried uploading it with another FTP client app downloaded in the play store and it worked correctly

Log:


B4X:
FTP.UploadFile(File.DirRootExternal & "/TTS2File/", filename, True, "/sdcard/" & filename)
B4X:
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

Nice! Works!!

I changed from:
FTP.UploadFile (File.DirRootExternal & "/ TTS2File /", filename, True, "/ sdcard /" & filename)

To:
FTP.UploadFile (File.DirRootExternal & "/ TTS2File /", filename, False, "/ sdcard /" & filename)

Binary files are not loaded correctly in ASCII mode :p
 

red30

Well-Known Member
Licensed User
Longtime User
I have an FTP server. If I connect through Total Commander or cmd windows, everything works, but does not work through the FTP.Initialize? What could it be?
B4X:
Sub Activity_Create(FirstTime As Boolean)
    If FirstTime Then
        FTP.Initialize("FTP", "xxx.xxx.xxx.xxx", 21, "user", "password")
        If FTP.IsInitialized=True Then
            Log("Hellow FTP!") ' this line OK
        End If
    End If
    Activity.LoadLayout("Main")
End Sub
Sub Button1_Click
    FTP.List("/")
End Sub
Sub FTP_ListCompleted (ServerPath As String, Success As Boolean, Folders() As FTPEntry, Files() As FTPEntry)
Log(ServerPath)
If Success = True Then
    Log("ok")
Else
    Log("no connection")
End If
End Sub
B4X:
** Activity (main) Create, isFirst = true **
Hellow FTP!
** Activity (main) Resume **
/
no connection
what am I doing wrong?
 

DonManfred

Expert
Licensed User
Longtime User
Status
Not open for further replies.
Top