Upload Http

Programmation d'applications complexes
Avatar de l’utilisateur
Thyphoon
Messages : 2706
Inscription : mer. 25/août/2004 6:31
Localisation : Eragny
Contact :

Upload Http

Message par Thyphoon »

Comme j'en ai marre de balader mes fichiers de chez moi au boulot et vis et versa je me suis que ça serait bien si je pouvais partager un repertoire sur un serveur sur le net. C'est faisable mais le problème c'est qu'au boulot le FTP est interdit...Et c'est là que j'ai eu une idée....
Faire une petite application qui chainé a un serveur PHP ferait sensiblement la même chose.
L'idée est simple. Sur le serveur j'ai un repertoire avec les fichiers
Mon programme questionne le serveur et retourne la liste des fichiers...
Si je double clic dans mon programme sur un fichier il se télécharge dans un repertoire temporaire et s'execute (ou s'ouvre avec l'application qui vas bien). Une fois refermé si le fichier a été modifier il est alors renvoyé !
Et c'est là ma question... Y a t'il moyen d'envoyer avec les commandes reseau un fichier a une page php qui remplacerait le l'ancien fichier dans le repertoire ?
Quelqu'un aurait une idée ?
Avatar de l’utilisateur
Thyphoon
Messages : 2706
Inscription : mer. 25/août/2004 6:31
Localisation : Eragny
Contact :

Message par Thyphoon »

Code : Tout sélectionner

;################################################################
;# 22/2/2006 - Upload file to web trough POST command | Pantcho #
;################################################################
EOL$ = Chr(13)+Chr(10)
URL$ = "127.0.0.1" ; the main domain
PATH$ = "/CgiFileIn.Php" ; or what ever script that accepts the enctype="multipart/form-data"
FullFileName$ = "c:\pb\text.txt" ; Full path+filename
ActionName$ = "file" ; this is important!! this action must be the same as  <form ... name="file">
FileHeader$ = "Content-Disposition: form-Data; name="+Chr(34)+ActionName$ + Chr(34) +"; filename="+Chr(34)+ FullFileName$+ Chr(34) +EOL$
FileHeader$ + "Content-Type: text/plain" ; <= Here change the content type regarding your file! (text,image etc...) we go on text
; ^^^ note: Havn't been tested with binary files.
Border$ = "23232323232" ; Border to the file data (Check RFC for more info)


If InitNetwork()
  conid.l = OpenNetworkConnection(URL$,80)
  If conid
      Debug "Connected"
      *Buffer = AllocateMemory(100000) ; some memory for our file buffer
      POST$ = "POST "+ PATH$ +" HTTP/1.0"  ; the Post command we are going to send to the server
   
      OpenFile(1,FullFileName$)
      Repeat
        Text$ = ReadString()
        FILE$ + Chr(13) + Chr(10)+Text$
      Until Eof(1)
      ; This is the border header for uploading
      FILE$ = "------"+Border$ + EOL$ + FileHeader$ +EOL$ + FILE$ + "------" + Border$ + "--"
      ; Back to post, while sending header with the correct content length (border+file+border)
      POST$ + EOL$ + "Content-Type: multipart/form-Data, boundary=----"+Border$ + EOL$ + "Content-Length: " + Str(Len(FILE$))
      POST$ + EOL$ + EOL$ + FILE$
      CloseFile(1)
      PokeS(*Buffer,"",0)
      PokeS(*Buffer,POST$,Len(POST$))
      SendNetworkData(conid,*Buffer,Len(POST$))
      Repeat
        Server$ = PeekS(*Buffer)
        Debug Server$
        res.l = ReceiveNetworkData(conid, *Buffer, 1000)
      Until Server$ = PeekS(*Buffer)
  Else
    Debug "NO CONNECTION"
  EndIf

EndIf
J'ai trouvé ce code sur le forum ...
Je vais essayer de vous pondre un code pour tester mon idée ... :D
Avatar de l’utilisateur
Thyphoon
Messages : 2706
Inscription : mer. 25/août/2004 6:31
Localisation : Eragny
Contact :

Message par Thyphoon »

voici le debut de mon programme
pour l'instant on peut regarder les fichier mais pas les modifier
ça marche tres bien avec les fichiers text mais pas avec les images quelqu'un a une idée ?
On peut aussi avancé dans les repertoires mais pas encore reculer !!

Qu'en pensez vous ?

Code : Tout sélectionner

Structure ProxyStructure
Adr.s
Port.l
login.s
password.s
EndStructure


Global Proxy.ProxyStructure


Structure FileStructure
Name.s
Size.l
Type.b
EndStructure

Global Dim File.FileStructure(100),NbFile,Folder.s,AddPath.s

;-Paramètre
Proxy\Adr=""
Proxy\Port=80
Proxy\login=""
Proxy\password=""
Folder="http://yann.lebrun.club.fr/temps/" ;Repertoire de base
AddPath=""; si jamais on navigue dans le repertoire de base

;- Window Constants

Enumeration
  #Main
EndEnumeration

;- Gadget Constants
;
Enumeration
  #ExplorerList
EndEnumeration

InitNetwork()
;-Download 

Procedure.s MyDownload(Url.s,UseProxy=#False)
  Protected Server.s,Port.l,conc$,enc$,Header.s,Res.l,*Buffer = AllocateMemory(1024),String.s,DataLength.l
  
  ;Si j'ai un Proxy je dois me connecter au Proxy
  If UseProxy=#True
    Path.s=Url
    Server.s=Proxy\Adr
    Port.l=Proxy\Port
    conc$=Proxy\login+":"+Proxy\password
    OutputBuffer = AllocateMemory(Len(conc$)*4)
    Base64Encoder(@conc$,Len(conc$),OutputBuffer,Len(conc$)*4)
    enc$=PeekS(OutputBuffer)
  
  ;Si je n'ai pas de proxy on se connecte directement au serveur  
  ElseIf UseProxy=#False
    Port=80
    Path.s = Url
    Url.s = RemoveString(Url,"http://",1)
     i = FindString(Url,"/",1)
     If i
       Server = Left(Url,i-1)
     Else
       Server = Url
     EndIf
  EndIf
  
  ;Connection au Serveur 
  ConnectionID = OpenNetworkConnection(Server, Port)
  If ConnectionID

    ;Creation de l'entête a envoyer
    Header ="GET "+Path+" HTTP/1.1"+#CRLF$
    
    If UseProxy=#True
      Header + "Proxy-Authorization: Basic "+enc$+#CRLF$
    Else
      Header + "Host: "+Server+#CRLF$+#CRLF$
    EndIf 
  
    Header+#CRLF$

    Res=SendNetworkData(ConnectionID,@Header,Len(Header))
  
    Delay(10)
    result = NetworkClientEvent(ConnectionID)
    Repeat ;On lit les données qui arrive
      DataLength = ReceiveNetworkData(ConnectionID,*Buffer,1024)
      String + PeekS(*Buffer,DataLength)
    Until DataLength<1024
    FreeMemory(*Buffer) ;POuff! Pu besoin on efface

    MessageRequester("Done!","Your Data" + Chr(13) + Chr(10) + Trim(String),0)
            
    ;C'est finit on se deconnecte
    CloseNetworkConnection(ConnectionID)
    debut = FindString(String, #CRLF$+#CRLF$, 1)
 
    String = Right(String, Len(String) - debut - 3)
    ProcedureReturn String
  EndIf
EndProcedure
;-Upload

Procedure Upload(File.s)
;################################################################
;# 22/2/2006 - Upload file to web trough POST command | Pantcho #
;################################################################

URL$ = "127.0.0.1" ; the main domain
PATH$ = "/CgiFileIn.Php" ; or what ever script that accepts the enctype="multipart/form-data"
FullFileName$ = "c:\pb\text.txt" ; Full path+filename
ActionName$ = "file" ; this is important!! this action must be the same as  <form ... name="file">
FileHeader$ = "Content-Disposition: form-Data; name="+Chr(34)+ActionName$ + Chr(34) +"; filename="+Chr(34)+ FullFileName$+ Chr(34) +#CRLF$
FileHeader$ + "Content-Type: text/plain" ; <= Here change the content type regarding your file! (text,image etc...) we go on text
; ^^^ note: Havn't been tested with binary files.
Border$ = "23232323232" ; Border to the file data (Check RFC for more info)


If InitNetwork()
  conid.l = OpenNetworkConnection(URL$,80)
  If conid
      Debug "Connected"
      *Buffer = AllocateMemory(100000) ; some memory for our file buffer
      POST$ = "POST "+ PATH$ +" HTTP/1.0"  ; the Post command we are going to send to the server
   
      OpenFile(1,FullFileName$)
      Repeat
        Text$ = ReadString(1)
        FILE$ + Chr(13) + Chr(10)+Text$
      Until Eof(1)
      ; This is the border header for uploading
      FILE$ = "------"+Border$ + #CRLF$ + FileHeader$ +#CRLF$ + FILE$ + "------" + Border$ + "--"
      ; Back to post, while sending header with the correct content length (border+file+border)
      POST$ + #CRLF$ + "Content-Type: multipart/form-Data, boundary=----"+Border$ + #CRLF$ + "Content-Length: " + Str(Len(FILE$))
      POST$ + #CRLF$ + #CRLF$ + FILE$
      CloseFile(1)
      PokeS(*Buffer,"",0)
      PokeS(*Buffer,POST$,Len(POST$))
      SendNetworkData(conid,*Buffer,Len(POST$))
      Repeat
        Server$ = PeekS(*Buffer)
        Debug Server$
        res.l = ReceiveNetworkData(conid, *Buffer, 1000)
      Until Server$ = PeekS(*Buffer)
  Else
    Debug "NO CONNECTION"
  EndIf

EndIf

EndProcedure

;-Procedure pour le Drag 'N Drop
Procedure.l DropFiles()
ProcedureReturn EventwParam()
EndProcedure

Procedure GetNumDropFiles(*dropFiles)
ProcedureReturn DragQueryFile_(*dropFiles, $FFFFFFFF, temp$, 0)
EndProcedure

Procedure.s GetDropFile(*dropFiles, index)
bufferNeeded = DragQueryFile_(*dropFiles, index, 0, 0)
For a = 1 To bufferNeeded: buffer$ + " ": Next ; Short by one character!
DragQueryFile_(*dropFiles, index, buffer$, bufferNeeded+1)
ProcedureReturn buffer$
EndProcedure

Procedure FreeDropFiles(*dropFiles)
DragFinish_(*dropFiles)
EndProcedure

;-Examine File
Procedure ExamineFile()
Url.s=Folder+"File.php?path="+AddPath
Debug url
Directory.s=MyDownload(Url)
P_Start=FindString(Directory,"<Thyphoon>",0)
P_End=FindString(Directory,"</Thyphoon>",0)
Directory.s=ReplaceString(Mid(Directory,P_Start,P_End-P_Start),"<Thyphoon>","")
NbFile = CountString(Directory,Chr(10))
For a=1 To NbFile
  Ligne.s=StringField(Directory,a,Chr(10))
  Debug Ligne
  File(a)\Name=StringField(Ligne,1,",")
  Select StringField(Ligne,3,",")
   Case "dir"
    File(a)\Type=#PB_DirectoryEntry_Directory
   Case "file"
    File(a)\Type=#PB_DirectoryEntry_File
  EndSelect
  File(a)\Size=Val(StringField(Ligne,2,","))
Next
EndProcedure



; Procedure ExamineFile()
;   Directory$ = "Temps\"   ; Énumère le contenu du répertoire C (Les sous-répertoires ne sont pas examinés) 
;   If ExamineDirectory(0, Directory$, "*.*")  
;     While NextDirectoryEntry(0)
;       If DirectoryEntryType(0) = #PB_DirectoryEntry_File Or DirectoryEntryType(0) = #PB_DirectoryEntry_Directory
;       NbFile+1
; 
;       File(NbFile)\Name=DirectoryEntryName(0)
;       File(NbFile)\Type=DirectoryEntryType(0)
;       File(NbFile)\Size=DirectoryEntrySize(0)
;       Debug File(NbFile)\Name
;       EndIf
;     Wend
;     FinishDirectory(0)
;   EndIf
; 
; EndProcedure

Procedure UpdateExlorerlist()
ClearGadgetItemList(#ExplorerList)
For z=1 To NbFile
  AddGadgetItem(#ExplorerList,-1,File(z)\Name+Chr(10)+Str(File(z)\Size)+" Ko")
Next
EndProcedure

Procedure Open_Window_0()
  If OpenWindow(#Main, 0, 0, 668, 300, "Synchro", #PB_Window_ScreenCentered| #PB_Window_SystemMenu | #PB_Window_SizeGadget | #PB_Window_TitleBar )
    DragAcceptFiles_(WindowID(#Main), 1)
    If CreateGadgetList(WindowID(#Main))
      ListIconGadget(#ExplorerList, 0, 0, 350, 65, "", 200,#PB_ListIcon_GridLines)
      AddGadgetColumn(#ExplorerList, 0, "Name ", 65)
      AddGadgetColumn(#ExplorerList, 1, "Size ", 65)
      AddGadgetColumn(#ExplorerList, 2, "Type ", 65)     
      AddGadgetColumn(#ExplorerList, 3, "Modified ", 65) 
    EndIf
  EndIf
EndProcedure

Procedure RunFile(n.l)
url.s=Folder+AddPath+File(n)\Name
Debug "Download..."+url
  String.s=MyDownload(url,#False)
  If CreateFile(0,GetFilePart(Url))
    WriteData(0,@String,Len(String))
    CloseFile(0)
  EndIf
Date_Before=GetFileDate(GetFilePart(Url), #PB_Date_Modified)  
RunProgram(GetFilePart(Url),"", "", #PB_Program_Wait)
Date_After=GetFileDate(GetFilePart(Url), #PB_Date_Modified) 
If Date_Before<>Date_After
 Debug "on Upload le fichier"
Else
 Debug "pas besoin d'uploader"
EndIf
EndProcedure

Open_Window_0()
ExamineFile()
UpdateExlorerlist()
Repeat 
  Event = WaitWindowEvent() 
  
  Select Event
    Case #PB_Event_SizeWindow
      ResizeGadget(#ExplorerList, 0, 0, WindowWidth(#Main), WindowHeight(#Main))
    
    Case #WM_DROPFILES
      *dropped = DropFiles()
      num.l = GetNumDropFiles(*dropped)
      f$ = ""
      For files = 0 To num - 1
      f$ + GetDropFile(*dropped, files) + Chr (13)
      Next
      MessageRequester("Drag 'n' Drop", Str (num) + " file (s) dropped:" + Chr (13) + Chr (13) + f$)
      FreeDropFiles(*dropped)
    Case #PB_Event_Gadget
      Select EventGadget()
        Case #ExplorerList
          Select EventType() 
            Case #PB_EventType_LeftDoubleClick
              ;On selectionne le fichier qu'on veut charger
              f=GetGadgetState(#ExplorerList)+1
              ;Si on a un fichier
              If f>0 And File(f)\Type=#PB_DirectoryEntry_File
                Debug "chargement du fichier"
                Thread = CreateThread(@RunFile(), f)
              ;Si on a un repertoir  
              ElseIf f>0 And File(f)\Type=#PB_DirectoryEntry_Directory
                Debug "changement de repertoir"
               ;Si on doit retourner en arrière dans le chemin
               If File(f)\Name=".."
               ;Sinon on rajoute le chemin
               Else
                AddPath+File(f)\Name+"/"
                ExamineFile()
                UpdateExlorerlist()
               EndIf
              EndIf
              
              
              
              ;
          EndSelect
          

      EndSelect

  EndSelect
  
   

Until  Event = #PB_Event_CloseWindow
Backup
Messages : 14526
Inscription : lun. 26/avr./2004 0:40

Message par Backup »

Thyphoon a écrit :ça marche tres bien avec les fichiers text mais pas avec les images quelqu'un a une idée ?
n'est-ce pas a cause de ça qu'il existe un mode Binaire, dans les logiciel de ftp ?

car par defaut le mode ascii ne contient pas tout les code, en effet il vont de
32 a 255 , mais qu'en est 'il de 0 a 32 ?? pour un programme ou une image par exemple !

c'est la raison pour laquel dans les NNtp (newsgroup) les images sont encodés ...
il existe différent mode "YENC" ou "begin 644" <-- j'ai oublié le nom (base64 je crois) , et "uuencode"

bref, on ne transfere pas une image ou un binaire, comme un text !!
car il il a d'autre valeur, que le code ascii ne sait pas gerer !

:D


voir ici :
http://fr.wikipedia.org/wiki/Base64
et la :
http://dictionnaire.phpmyvisites.net/de ... c-9316.htm

et la http://www.exit109.com/~jeremy/news/bin ... oding.html
Je te conseille de t'intéresser au Yenc qui respect le mode 8 bits :D
Avatar de l’utilisateur
Thyphoon
Messages : 2706
Inscription : mer. 25/août/2004 6:31
Localisation : Eragny
Contact :

Message par Thyphoon »

Merci Dobro. J'ai trouvé la solution... pas besoin d'encoder un fichier binaire...mon erreur était de stocker dans un "string"...en stockant dans un AllocateMemory ça marche tres bien... :oP

J'ai retirer la gestion du proxy pour l'instant, faudra que je le rajoute apres. Et il me reste a tester le retransfert des fichiers dans l'autre sens si ils sont modifier. une fois ça fait. Je reposterais le code.
Avatar de l’utilisateur
Thyphoon
Messages : 2706
Inscription : mer. 25/août/2004 6:31
Localisation : Eragny
Contact :

Message par Thyphoon »

Si le téléchargement fonctionne maintenant parfaitement

Le code que j'ai trouvé pour uploader ne fonctionne pas... :(

Quelqu'un sait comment je pourrais faire ?
Répondre