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:

imgsimonebiliato

Well-Known Member
Licensed User
Longtime User
Is the download successful? If yes then this error might be related to a different app.

The download is success only for the first few times, but then no more
 

imgsimonebiliato

Well-Known Member
Licensed User
Longtime User
Can you post the relevant code?

B4X:
Sub btSrc_click
gFtp.DeleteRows

If pathDownload = "" Then
   Msgbox ("Selezionare macchina", "")
   Return
Else
   ProgressDialogShow ( "Ricerca in corso")
   FTP.List(pathDownload)
End If
End Sub

Sub ftp_ListCompleted(ServerPath As String, Success As Boolean, Folders() As FTPEntry, Files() As FTPEntry)
Dim i As Int
Dim n As Int
n = 0

Dim currentFile(3) As String
If Success = False Then
    Msgbox ("Nessun file", "Errore")
    Log(LastException)
Else        
   For i = 0 To Files.Length - 1
      If (Files(i).Name.ToUpperCase.Contains (edFlt.Text.ToUpperCase.Trim)) OR (edFlt.Text = "") Then
          n = n + 1
         If n <= 100 Then
            currentFile(0) = Files(i).Name
            currentFile(1) = Files(i).Size
            currentFile(2) = DateTime.Date(Files(i).Timestamp)
            gFtp.AppendRow( currentFile )
         End If
      End If
    Next
End If
 

imgsimonebiliato

Well-Known Member
Licensed User
Longtime User
Where is the download code?

B4X:
Sub ftp_downloadcompleted(serverpath As String, success As Boolean)
Log (serverpath & ", Success=" & success)

stringPath = File.DirRootExternal & "/" & ftpDownFileSelected

If success = False Then Msgbox (LastException.Message, "")

fileToWrite.Initialize(File.DirRootExternal & "/ProgTor", fileNameDownload, True)

If Msgbox2("Trasferire " & ftpDownFileSelected & " alla macchina?", "Conferma Invio File", "Si", "", "No", Null) = DialogResponse.POSITIVE Then            
   s1.Initialize("s1")
   s1.Connect(host, porta, timeout)
Else            
   Return
End If
End Sub


Sub s1_connected (stato As Boolean)
Dim in As InputStream
Dim out As OutputStream
Dim i As Int
Dim size, fileSize As Int

If stato = False Then
   Msgbox ( "File non trasferito", "Macchina non connessa")
   Return
End If

out = s1.OutputStream

fileSize = fileToWrite.size

Dim dadda(fileSize) As Byte
fileToWrite.ReadBytes(dadda, 0, fileSize, 0)
out.WriteBytes(dadda, 0, fileSize-1 )

If stato Then
   Msgbox("File trasferito correttamente", "")
End If

s1.Close
End Sub

s1 is a socket
 

imgsimonebiliato

Well-Known Member
Licensed User
Longtime User
Hi,
how can I check if a file exist in the ServerPath?
 

padvou

Active Member
Licensed User
Longtime User
Is it possible to have the filename in the following subs:
FTP_UploadProgress
FTP_UploadCompleted
 

cmartins

Member
Licensed User
Longtime User
I am tring to dowload usind 4 devices using a 50mb file. some of those devices stop the doanload and frezee. I can see in the FTP log close connection.

to try connect again only restart the device.

ftp log
[INFO ]Close connection : 10.0.50.111 - [email protected]
[INFO ]File download : [email protected] - /GOPR0114.MP4

what can I do to fix it?
 

Libertino

New Member
Licensed User
Longtime User
Do you see anything in the device log?

You should use a Service for this download:
- Call Service.StartForeground
- Acquire a partial lock with PhoneWakeState.

I'm using Net (version 1.20).
The problem is that it is compressing the spaces in the download.
Ex:
Before: 02100007PLIMOR PORTO ALEGRE
After download: 02100007PLIMOR PORTO ALEGRE

Please help me.
 

Libertino

New Member
Licensed User
Longtime User
I'm using Net (version 1.20).
The problem is that it is compressing the spaces in the download.
Ex:
Before: 02100007PLIMOR PORTO ALEGRE
After download: 02100007PLIMOR PORTO ALEGRE

Please help me.

Escuse me - the FTP is ok.
 

David Hawkins

Active Member
Licensed User
Longtime User
The problem was the path on my server !

Thanks Erel,

you are really good

:sign0188:
Hi Erel

I hope you can help me I would like to download several files at a time and whilst I have managed to achieve this it is very in-elegant and appears to download both files I have waiting twice. Can you give me a pointer to the proper way to achieve this please.

Regards

David
 

David Hawkins

Active Member
Licensed User
Longtime User
Hi Erel

I hope you can help me I am trying to download two files at the same time can you give me a pointer to the proper way to achieve this please. I have sort of succeeded but it very cumbersome and appears to download both files twice, which I am sure is not correct.

Regards

David
 
Status
Not open for further replies.
Top