1. Download the free trial version

Tutorial Android FTP tutorial

Discussion in 'Tutorials & Examples' started by Erel, Jul 25, 2011.

  1. Erel

    Erel Administrator Staff Member Licensed User

    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.
    Code:
    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.

    Code:
    FTP.DownloadFile("/somefolder/files/1.zip"FalseFile.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.
    Code:
    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:
    Code:
    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
     
    gudino jose luis likes this.
  2. carlosmdg

    carlosmdg Member Licensed User

    I need an example file please!

    I copy the indications but dont work me
     
  3. Erel

    Erel Administrator Staff Member Licensed User

    What error do you get?
     
  4. AscySoft

    AscySoft Active Member Licensed User

    Does this library knows sftp protocol? Sorry, this is my first day with android/b4a :D
     
  5. Erel

    Erel Administrator Staff Member Licensed User

    No, only FTP is supported.
     
  6. AscySoft

    AscySoft Active Member Licensed User

    Then I must encode/zip files manually for strong security reason then upload them using ftp! Coud you point to a solution/link that sound anything like that? I mean, zip with password/encode files etc
     
  7. carlosmdg

    carlosmdg Member Licensed User

    I'd like to sync through ftp but not responding.
    The code i have is the following:


    Code:
    Sub Process_Globals
    ...
       
    Dim FTP As FTP
    End Sub

    Code:
    Sub Activity_Create(FirstTime As Boolean)
       Activity.AddMenuItem2(
    "Sincronizar","update2",LoadBitmap(File.DirAssets,"refresh.png"))
       
    If FirstTime Then
          
    FTP.Initialize("FTP""ftp.xxx"21"user""pass")
       
    End If
    End Sub


    Code:
    Sub Update2_click
       sdRoot = 
    File.DirDefaultExternal & "/"
       
    FTP.DownloadFile("/Team/prestadores.txt"False, sdRoot, "PRESTADORESFTP.txt")
       
    FTP.UploadFile(sdRoot,"Reg" & d.GetDeviceId  & ".txt"True"/Team/RegTmp" & d.GetDeviceId  & ".txt")
    End Sub
    when in using debug mode, i see this:

    Code:
    DownloadService [donesuccessfully=false, hc=anywheresoftware.b4a.http.HttpClientWrapper@44d029d0, jobstatus=0 , notification=1(NotificationNot initialized, status_done=2, status_none=0, status_working=1, target=(OutputStreamNot initialized, url=
    I test the apk in my dispositive but dont work
     
  8. Erel

    Erel Administrator Staff Member Licensed User

    The DownloadService is not related. It is a code module that you have added to your project.

    Have you added the FTP_DownloadCompleted / FTP_UploadCompleted subs? Without them you will not see any result.
     
  9. carlosmdg

    carlosmdg Member Licensed User

    I have a Service module called DownloadService, it's the same like the example http://www.basic4ppc.com/forum/basic...#post43109

    And I have this subs...

    Code:
    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

    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
    When i run the project step by step, never calls to DownloadService module
     
  10. Erel

    Erel Administrator Staff Member Licensed User

    Try to create a simple project which downloads a single file and see if it works. Make sure to check the logs (including the unfiltered logs if you don't see any message).
     
  11. carlosmdg

    carlosmdg Member Licensed User

    I did this, but the problem persist

    I Attach a project.
    The DownloadService requires two variables: URL and TARGET, the "TARGET" i do know what is, but the "URL" i don't know because i'm trying to download from FTP instead of URL
    What variable must i asign to Download Service.URL ?
     

    Attached Files:

    Last edited: Aug 2, 2011
  12. Erel

    Erel Administrator Staff Member Licensed User

    In order to upload your project you should choose File - Export to zip. The current zip file is missing several files.

    DownloadService cannot be used with FTP. It is a way to download files with HTTP.
     
  13. danoptic

    danoptic Member Licensed User

    I doesnt work for me - here is the code

    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
    activity.LoadLayout("test")
    End Sub



    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


    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
    Sub UploadButton_Click
    FTP.UploadFile(File.DirRootExternal, "1.jpg", True, "/myandroidapp/1.jpg")
    End Sub
    Sub DownloadButton_Click
    FTP.DownloadFile("/myandroidapp/1.zip", False, File.DirRootExternal, "1.zip")
    End Sub


    the error messages:

    LogCat connected to: 3333B9BC2E5600EC
    --------- beginning of /dev/log/main
    ** Activity (main) Create, isFirst = true **
    ** Activity (main) Resume **
    /myandroidapp/1.zip, Success=false
    java.lang.RuntimeException: Error retrieving file.
    550 /myandroidapp/1.zip: The system cannot find the path specified.
    /myandroidapp/1.jpg, Success=false
    java.lang.RuntimeException: Error uploading file.
    550 /myandroidapp/1.jpg: Access is denied.
     
  14. Erel

    Erel Administrator Staff Member Licensed User

    Based on the logs it seems that the path to the server file is not correct.
     
  15. danoptic

    danoptic Member Licensed User

    explain please

    The ftp adress is the sam as i entr in filezilla
    the folder is the next folder undr the root
    and what aboutt the upload error?
     
  16. Erel

    Erel Administrator Staff Member Licensed User

    It is possible that filezilla is configured to start in some default path.
    There is an access denied message in the log when you try to upload. This can happen because your user do not have the right permission or that you are trying to upload the the wrong path.
     
  17. carlosmdg

    carlosmdg Member Licensed User

    Sorry, here is all project
     

    Attached Files:

  18. Erel

    Erel Administrator Staff Member Licensed User

    I ran your program and it seems to run fine.
    It download the file and printed this message to the log:
    Team/prestadores.txt, Success=true
     
  19. carlosmdg

    carlosmdg Member Licensed User

    ja!
    I ran the program and when i click on the button the FTP.Downloadfile does nothing. Never enters to FTP_DownloadCompleted

    but the FTP.DownloadFile creates the file "PRESTATUTI" without content
     
  20. danoptic

    danoptic Member Licensed User

    The problem was the path on my server !

    Thanks Erel,

    you are really good

    :sign0188:
     

Share This Page

Loading...