Télécharger fichier via FTP

Codes specifiques à Windows
hub73
Messages : 126
Inscription : sam. 16/janv./2021 20:17

Télécharger fichier via FTP

Message par hub73 »

Bonjour.
- Je cherche un exemple de code pour télécharger un fichier via FTP. Il n'y a pas d"exemple dans la documentation officielle. Et je me perds dans l'organisation des commandes.
- FTP est plus rapide que HTTP ? (pour télécharger une tout petit fichier texte).
- Pour info. J'ai un fichier texte qui contient une commande sur mon site internet du genre 'pause'. Le programme doit télécharger toutes les 5 secondes ce fichier pour examiner la commande à l'intérieur et la réaliser.
Merci.
hub73
Messages : 126
Inscription : sam. 16/janv./2021 20:17

Re: Télécharger fichier via FTP

Message par hub73 »

Avant en HTTP j'avais çà mais ca fonctionne mal

Code : Tout sélectionner

   Procedure Gerer_action_serveur()
     
     Define URL$
     Define Fichier$
     Define Action$
     
     URL$ = "https://www.lesfloralies.info/diffusion/serveur.txt"
     
     Fichier$= GetHomeDirectory() + "/tempo.txt"
     
     If ReceiveHTTPFile (Url$, Fichier$)
       
       If  ReadFile (0, Fichier$)
         Action$ = ReadString (0)
       EndIf
       
     Else
       
       Action$ = "ERREUR"
       
     EndIf
     
     ;Debug "Action=" + Action$
     
     If Action$ <> "ERREUR"
     
       Select Action$
           
         Case "PLAY"
  			      If gEtat_lecture = #LECTURE_LISTE_OFF
  			        gEtat_lecture = #LECTURE_LISTE_INIT
  			        Envoyer_message_retour_diffusion ("Demande de lancement de lecture.")
  			      Else
  			        Envoyer_message_retour_diffusion ("La Playlist est déjà en cours de lecture !")
  			      EndIf
  			      Effacer_commande_diffusion ()
  			      
         Case "PAUSE"  
           Pauser_lecture()
           Effacer_commande_diffusion ()
           
         Case "DIRECT"  
           Pauser_lecture()
           Effacer_commande_diffusion ()
           
         Case "REPRISE"
           Reprendre_lecture()
           Effacer_commande_diffusion ()
           
         Case "STOP"
           Arreter_son()
           Effacer_commande_diffusion ()
           
       EndSelect
       
     EndIf
     
   EndProcedure
Marc56
Messages : 2148
Inscription : sam. 08/févr./2014 15:19

Re: Télécharger fichier via FTP

Message par Marc56 »

Bonsoir,

Si tu n'a besoin que de lire le contenu d'un fichier distant, tu peux utiliser HTTPRequest() qui te permet de lire et mettre le contenu dans une variable en une seule opération, sans avoir à passer par un fichier ou utiliser ReceiveHTTPMemory et PeekS.

Voici ton exemple (que j'ai éclairci pour tester en local et en réel)

Code : Tout sélectionner

Procedure Gerer_action_serveur()
    
    Define URL$
    Define Action$
    
    HTTPRequest = HTTPRequest(#PB_HTTP_Get, "http://127.0.0.1/diffusion/serveur.txt")
    If HTTPRequest 
        Action$ = HTTPInfo(HTTPRequest, #PB_HTTP_Response)
    Else
        Debug "Pas d'accès au serveur"
    EndIf
    
    If Action$ <> "ERREUR"
        
        Select Action$
                
            Case "PLAY"
                Debug "PLAY"
                
            Case "PAUSE"  
                Debug "PAUSE"
                
            Case "DIRECT"  
                Debug "DIRECT"
                
            Case "REPRISE"
                Debug "REPRISE"
                
            Case "STOP"
                Debug "STOP"
                
            Default
                Debug "RIEN"
        EndSelect
        
    EndIf
    
EndProcedure

Gerer_action_serveur()
FTP n'est pas plus rapide que HTTP, il est simplement mieux adapté au transferts de fichiers. Il utilise aussi deux canaux (transfert et commandes) ce qui permet de contrôler sans attendre la fin d'un transfert.

Cela dit, si tu as la main sur le serveur, tu peux aussi écrire une petite application client/serveur (voir les exemples NetworkClient.pb et NetworkServer.pb de la librairie Network)

:wink:
Dernière modification par Marc56 le jeu. 27/mai/2021 10:39, modifié 1 fois.
hub73
Messages : 126
Inscription : sam. 16/janv./2021 20:17

Re: Télécharger fichier via FTP

Message par hub73 »

Cool HTTPRequest()dans la variable !
Avatar de l’utilisateur
Ar-S
Messages : 9478
Inscription : dim. 09/oct./2005 16:51
Contact :

Re: Télécharger fichier via FTP

Message par Ar-S »

+1 ^pour HTTPRequest
si tu veux tout de même telech en mémoire un fichier ReceiveHTTPMemory fait l'affaire.

Code : Tout sélectionner

InitNetwork()

Procedure.s CatchTWevxt(url$)
    *BufferV = ReceiveHTTPMemory(url$)
    If *BufferV
        Taille = MemorySize(*BufferV)
        NewV$ = PeekS(*BufferV, Taille, #PB_UTF8)
        FreeMemory(*BufferV)
        ProcedureReturn NewV$
    EndIf
EndProcedure


;example 
url$ = "http://52.87.135.24/json-files/events.json" ; trouvé au pif sur le web
Debug CatchTWevxt(url$)
~~~~Règles du forum ~~~~
⋅.˳˳.⋅ॱ˙˙ॱ⋅.˳Ar-S ˳.⋅ॱ˙˙ॱ⋅.˳˳.⋅
W11x64 PB 6.x
Section HORS SUJET : ICI
LDV MULTIMEDIA : Dépannage informatique & mes Logiciels PB
UPLOAD D'IMAGES : Uploader des images de vos logiciels
hub73
Messages : 126
Inscription : sam. 16/janv./2021 20:17

Re: Télécharger fichier via FTP

Message par hub73 »

Je ne sais pas pourquoi mais ReceiveHTTPMemory ne fonctionnait pas bien lors de mes tests. Certainement pas la fonction mais des soucis du côté de mon serveur.
hub73
Messages : 126
Inscription : sam. 16/janv./2021 20:17

Re: Télécharger fichier via FTP

Message par hub73 »

Dans tous les cas grand merci à vous deux.
Mesa
Messages : 1098
Inscription : mer. 14/sept./2011 16:59

Re: Télécharger fichier via FTP

Message par Mesa »

Kenmo a fait ce code, on le trouve quelque part sur github...

Code : Tout sélectionner

; +---------------+
; | FTPHelper.pbi |
; +---------------+
; | 2015.06.05 . Creation (PureBasic 5.31)
; | 2017.05.22 . Cleanup
; | 2018.06.15 . Added QuickFTPUpload()
; | 2018.07.07 . Moved RemoteFile formatting from QuickUpload into Upload
; | 2018.11.08 . Upload and Download now default to current FTP/Local dirs
; | 2018.11.09 . Added OpenFTPFromFile
; | 2020-06-19 . Remove Preferences calls (only use helper File functions)

;-
CompilerIf (Not Defined(__FTPHelper_Included, #PB_Constant))
#__FTPHelper_Included = #True

CompilerIf (#PB_Compiler_IsMainFile)
  EnableExplicit
CompilerEndIf



;- Procedures (Private)

Procedure.i _FTPHelper_FindGroup(FN.i, GroupName.s)
  Protected Result.i = #False
  FileSeek(FN, 0)
  ReadStringFormat(FN)
  If (GroupName)
    GroupName = LCase("[" + Trim(GroupName) + "]")
    While (Not Eof(FN))
      Protected Line.s = ReadString(FN)
      If (LCase(Trim(Line)) = GroupName)
        Result = #True
        Break
      EndIf
    Wend
  EndIf
  ProcedureReturn (Result)
EndProcedure

Procedure.s _FTPHelper_FindString(FN.i, Key.s, DefaultValue.s = "")
  Protected Result.s = DefaultValue
  Protected Location.i = Loc(FN)
  Key = LCase(Trim(Key))
  While (Not Eof(FN))
    Protected Line.s = ReadString(FN)
    If (Left(LTrim(Line), 1) = ";")
      Continue
    ElseIf (Left(LTrim(Line), 1) = "[")
      Break
    Else
      Protected i.i = FindString(Line, "=")
      If (i)
        If (LCase(Trim(Left(Line, i-1))) = Key)
          Result = Trim(Mid(Line, i+1))
          Break
        EndIf
      EndIf
    EndIf
  Wend
  FileSeek(FN, Location)
  ProcedureReturn (Result)
EndProcedure



;-
;- Procedures (Public)

Procedure.i ChangeFTPDirectory(FTP.i, Directory.s, Create.i = #False)
  Protected Result.i = #False
  If (IsFTP(FTP))
    If (CheckFTPConnection(FTP))
      If (Directory)
        ReplaceString(Directory, "\", "/", #PB_String_InPlace)
        Directory = RTrim(Directory, "/") + "/"
        Protected Current.s
        Current = RTrim(GetFTPDirectory(FTP), "/") + "/"
        If (Left(Directory, 1) <> "/")
          Directory = Current + Directory
        EndIf
        If (Current <> Directory)
          Result = #True
          While (Current <> Left(Directory, Len(Current)))
            If (Not SetFTPDirectory(FTP, ".."))
              Result = #False
              Break
            EndIf
            Current = RTrim(GetFTPDirectory(FTP), "/") + "/"
          Wend
          If (Result)
            While (Len(Current) < Len(Directory))
              Protected SUB.s
              SUB = StringField(Mid(Directory, Len(Current) + 1), 1, "/")
              If (Create)
                CreateFTPDirectory(FTP, SUB)
              EndIf
              If (Not SetFTPDirectory(FTP, SUB))
                Result = #False
                Break
              EndIf
              Current = RTrim(GetFTPDirectory(FTP), "/") + "/"
            Wend
          EndIf
        Else
          Result = #True
        EndIf
      Else
        Result = #True
      EndIf
    EndIf
  EndIf
  ProcedureReturn (Result)
EndProcedure

Procedure.i UploadFTPFile(FTP.i, LocalFile.s, RemoteFile.s = "")
  Protected Result.i = #False
  If (IsFTP(FTP))
    If (LocalFile)
      If (RemoteFile = "")
        ;RemoteFile = "/" + GetFilePart(LocalFile)
        RemoteFile = GetFTPDirectory(FTP) + "/" + GetFilePart(LocalFile)
      ElseIf (Right(RemoteFile, 1) = "/")
        RemoteFile + GetFilePart(LocalFile)
      EndIf
      If (ChangeFTPDirectory(FTP, GetPathPart(RemoteFile), #True))
        Result = Bool(SendFTPFile(FTP, LocalFile, GetFilePart(RemoteFile)))
      EndIf
    EndIf
  EndIf
  ProcedureReturn (Result)
EndProcedure

Procedure.i DownloadFTPFile(FTP.i, RemoteFile.s, LocalFile.s = "")
  Protected Result.i = #False
  If (IsFTP(FTP))
    If (RemoteFile)
      If (GetPathPart(RemoteFile) = "")
        RemoteFile = GetFTPDirectory(FTP) + "/" + RemoteFile
      EndIf
      If (LocalFile = "")
        LocalFile = GetCurrentDirectory() + GetFilePart(RemoteFile)
      EndIf
      If (ChangeFTPDirectory(FTP, GetPathPart(RemoteFile), #False))
        Result = Bool(ReceiveFTPFile(FTP, GetFilePart(RemoteFile), LocalFile))
      EndIf
    EndIf
  EndIf
  ProcedureReturn (Result)
EndProcedure

Procedure.i QuickFTPUpload(File.s, Server.s, RemoteFile.s = "", User.s = "", Pass.s = "", Port.i = 21, Passive.i = #True)
  Protected Result.i = #False
  If (File And (FileSize(File) >= 0) And Server)
    If (InitNetwork())
      Protected FTP.i = OpenFTP(#PB_Any, Server, User, Pass, Passive, Port)
      If (FTP)
        Result = UploadFTPFile(FTP, File, RemoteFile)
        CloseFTP(FTP)
      EndIf
    EndIf
  EndIf
  ProcedureReturn (Result)
EndProcedure

Procedure.s FTPDirectoryContents(FTP.i, IncludeParent.i = #False)
  Protected Result.s
  If (ExamineFTPDirectory(FTP))
    While (NextFTPDirectoryEntry(FTP))
      Protected Name.s = FTPDirectoryEntryName(FTP)
      Select (Name)
        Case "."
          ; skip
        Case".."
          If (IncludeParent)
            Result + #LF$ + ".."
          EndIf
        Default
          Result + #LF$ + FTPDirectoryEntryName(FTP)
          If (FTPDirectoryEntryType(FTP) = #PB_FTP_Directory)
            Result + "/"
          EndIf
      EndSelect
    Wend
    FinishFTPDirectory(FTP)
  EndIf
  ProcedureReturn (Mid(Result, 2))
EndProcedure

Procedure.i OpenFTPFromFile(FTP.i, File.s, Group.s = "")
  Protected Result.i = #Null
  Protected FN.i = ReadFile(#PB_Any, File)
  If (FN)
    If ((Group = "") Or (_FTPHelper_FindGroup(FN, Group)))
      Protected RemoveChar.s = Left(_FTPHelper_FindString(FN, "rc"), 1)
      Protected Server.s  = RemoveString(_FTPHelper_FindString(FN, "s"), RemoveChar)
      Protected User.s    = RemoveString(_FTPHelper_FindString(FN, "u"), RemoveChar)
      Protected Pass.s    = RemoveString(_FTPHelper_FindString(FN, "p"), RemoveChar)
      Protected Dir.s     = RemoveString(_FTPHelper_FindString(FN, "d"), RemoveChar)
      Protected Port.i    = Val(_FTPHelper_FindString(FN, "port", "21"))
      Protected Passive.i = Bool(Val(_FTPHelper_FindString(FN, "passive", "1")))
      If (FindString(Server, "://"))
        Server = StringField(Server, 2, "://")
      EndIf
      Server = RTrim(Server, "/")
      If (Server And User And Pass And (Port > 0))
        Result = OpenFTP(FTP, Server, User, Pass, Passive, Port)
        PokeS(@Pass, Space(Len(Pass)))
        If (Result)
          If (FTP = #PB_Any)
            FTP = Result
          EndIf
          If (Dir)
            If (Right(Dir, 1) <> "/")
              Dir + "/"
            EndIf
            If (ChangeFTPDirectory(FTP, Dir, #False))
              ;
            Else
              CloseFTP(FTP)
              Result = #Null
            EndIf
          EndIf
        EndIf
      EndIf
    EndIf
    CloseFile(FN)
  EndIf
  ProcedureReturn (Result)
EndProcedure






;-
;- Demo Program

CompilerIf (#PB_Compiler_IsMainFile)
  DisableExplicit
  
  ; ==========================================
  ; Fill these in to test!
  Server.s   = ""
  User.s     = "myUser"
  Password.s = "myPassword"
  RemoteFile.s  = "/www/files/myFile.dat"
  ; ==========================================
  
  Passive.i  = #True
  Port.i     =  21
  
  LocalFile.s   = GetTemporaryDirectory() + GetFilePart(RemoteFile)
  RemoteFile2.s = RemoteFile + ".new"
  
  If (Server)
    If InitNetwork()
      Debug "Connecting to " + Server + "..."
      If OpenFTP(0, Server, User, Password, Passive, Port)
        
        Debug "OK" + #LF$ + "Downloading file..."
        If (DownloadFTPFile(0, RemoteFile, LocalFile))
          Debug "OK" + #LF$ + "Uploading file..."
          If (UploadFTPFile(0, LocalFile, RemoteFile2))
            Debug "OK" + #LF$ + "Resetting to root directory..."
            If (ChangeFTPDirectory(0, "/"))
              Debug "OK" + #LF$ + "Done"
            Else
              Debug "Failed!"
            EndIf
          Else
            Debug "Failed!"
          EndIf
        Else
          Debug "Failed!"
        EndIf
        
        CloseFTP(0)
      Else
        Debug "Could not open FTP connection!"
      EndIf
    EndIf
  Else
    Debug "Please specify a server and username in code"
  EndIf
  
CompilerEndIf
CompilerEndIf
;-]
M.
Répondre