Forum |  HardWare.fr | News | Articles | PC | S'identifier | S'inscrire | Shop Recherche
1569 connectés 

  FORUM HardWare.fr
  Programmation
  C#/.NET managed

  automatiser l'envoi d'un fichier à un serveur jsp

 


 Mot :   Pseudo :  
 
Bas de page
Auteur Sujet :

automatiser l'envoi d'un fichier à un serveur jsp

n°1860774
toti3221
Posté le 12-03-2009 à 15:32:21  profilanswer
 

Salut  
Voici mon problème que je n'arrive pas à résoudre
j'ai une servlet java qui fait l'upload d'un fichier  (marche à 100%)
j'ai deux pages jsp  
la première est : index.jsp  

Code :
  1. <form  method="post" enctype="multipart/form-data" name="form1" action="success.jsp">
  2.           <table width="386" border="1">
  3.             <tr>
  4.               <td width="120">photo : </td>
  5.               <td width="250"><input  type="file" name="photo"></td>
  6.             </tr>
  7.        
  8.            
  9.             <tr>
  10.               <td><input type="submit"></td>
  11.               <td>&nbsp;</td>
  12.             </tr>
  13.     </table>
  14.     </form>


 
la deuxieme fait la recuperation du fichier et l'enregistre sur le disque (j'ai un serveur tomcat)
 
je cherche à automatiser la methode d'upload  
à partir de mon application (client lourd avec (vb.net ou c#) en cliquant sur un bouton je fais l'upload j'ai cherché sur le net  
j'ai trouvé deux essai  
le prémier : http://forum.hardware.fr/hfr/Progr [...] 9103_1.htm  
le deuxieme est le suivant  
 

Code :
  1. Imports Microsoft.Win32
  2. Imports System.IO
  3. Imports System.Net
  4. Imports System.Web
  5. Imports System.Threading
  6. Imports System.Reflection
  7. Public Class UploadForm
  8.     Private _userAgent As String = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)"
  9.     Private _accept As String = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*"
  10.     Private _accept_encoding As String = "gzip, deflate"
  11.     Private _accept_charset As String = "ISO-8859-1,utf-8;q=0.7,*;q=0.7"
  12.     Private _referer As String
  13.     Private _boundary As String = "---------------------------" & DateTime.Now.Ticks.ToString("x" )
  14.     Private _contentType As String
  15.     Private _contentLength As Integer
  16.     Private _querystring As New Specialized.NameValueCollection()
  17.     Private _isBusy As Boolean
  18.     Private _cancel As Boolean
  19.     Const BufferSize As Integer = &H2000 '2048
  20.     Private _waitHandle As RegisteredWaitHandle
  21.     Public Delegate Sub UploadCompletedHandler(ByVal e As UploadCompletedArgs)
  22.     Public Delegate Sub UploadProgressHandler(ByVal bytesRead As Integer, ByVal totalBytes As Integer)
  23.     Public Event UploadProgress(ByVal bytesRead As Integer, ByVal totalBytes As Integer)
  24.     Public Event UploadCompleted(ByVal e As UploadCompletedArgs)
  25.     Private Class DatasToSend
  26.         Public HeaderBytes() As Byte
  27.         Public FileStream As FileStream
  28.         Public FooterBytes() As Byte
  29.         ReadOnly Property Length() As Integer
  30.             Get
  31.                 Return HeaderBytes.Length + FooterBytes.Length + FileStream.Length
  32.             End Get
  33.         End Property
  34.     End Class
  35.     ''' <summary>
  36.     ''' DEFAULT
  37.     ''' </summary>
  38.     ''' <value></value>
  39.     ''' <returns></returns>
  40.     ''' <remarks></remarks>
  41.     Public ReadOnly Property Boundary() As String
  42.         Get
  43.             Return _boundary
  44.         End Get
  45.     End Property
  46.     Public Property QueryString() As Specialized.NameValueCollection
  47.         Get
  48.             Return _querystring
  49.         End Get
  50.         Set(ByVal value As Specialized.NameValueCollection)
  51.             _querystring = value
  52.         End Set
  53.     End Property
  54.     ''' <summary>
  55.     ''' DEFAULT
  56.     ''' </summary>
  57.     ''' <value></value>
  58.     ''' <returns></returns>
  59.     ''' <remarks></remarks>
  60.     Public ReadOnly Property ContentLength() As Integer
  61.         Get
  62.             Return _contentLength
  63.         End Get
  64.     End Property
  65.     Public Property Referer() As String
  66.         Get
  67.             Return _referer
  68.         End Get
  69.         Set(ByVal value As String)
  70.             _referer = value
  71.         End Set
  72.     End Property
  73.     ''' <summary>
  74.     ''' DEFAULT
  75.     ''' </summary>
  76.     ''' <value></value>
  77.     ''' <returns></returns>
  78.     ''' <remarks></remarks>
  79.     Public ReadOnly Property AcceptEncoding() As String
  80.         Get
  81.             Return _accept_encoding
  82.         End Get
  83.     End Property
  84.     ''' <summary>
  85.     ''' DEFAULT
  86.     ''' </summary>
  87.     ''' <value></value>
  88.     ''' <returns></returns>
  89.     ''' <remarks></remarks>
  90.     Public ReadOnly Property Accept() As String
  91.         Get
  92.             Return _accept
  93.         End Get
  94.     End Property
  95.     ''' <summary>
  96.     ''' DEFAULT
  97.     ''' </summary>
  98.     ''' <value></value>
  99.     ''' <returns></returns>
  100.     ''' <remarks></remarks>
  101.     Public ReadOnly Property UserAgent() As String
  102.         Get
  103.             Return _userAgent
  104.         End Get
  105.     End Property
  106.     ''' <summary>
  107.     ''' DEFAULT
  108.     ''' </summary>
  109.     ''' <value></value>
  110.     ''' <returns></returns>
  111.     ''' <remarks></remarks>
  112.     Public ReadOnly Property AcceptCharset() As String
  113.         Get
  114.             Return _accept_charset
  115.         End Get
  116.         'Set(ByVal value As String)
  117.         '    _accept_charset = value
  118.         'End Set
  119.     End Property
  120.     Public ReadOnly Property IsBusy() As Boolean
  121.         Get
  122.             Return _isBusy
  123.         End Get
  124.     End Property
  125.     Private ReadOnly Property WaitHandle() As RegisteredWaitHandle
  126.         Get
  127.             Return _waitHandle
  128.         End Get
  129.     End Property
  130.     Private Sub SetCompleted()
  131.         SyncLock Me
  132.             _cancel = False
  133.             _isBusy = False
  134.         End SyncLock
  135.     End Sub
  136.     Private Sub CheckBusy()
  137.         If _isBusy Then
  138.             Throw New NotSupportedException("1 seule opération asynchrone à la fois!" )
  139.         End If
  140.     End Sub
  141.     Private Sub SetBusy()
  142.         SyncLock Me
  143.             CheckBusy()
  144.             _isBusy = True
  145.         End SyncLock
  146.     End Sub
  147.     Private Sub SetCancel()
  148.         SyncLock Me
  149.             _cancel = True
  150.         End SyncLock
  151.     End Sub
  152.     ''' <summary>
  153.     ''' Annule Lopération asynchrone en cour
  154.     ''' </summary>
  155.     ''' <remarks></remarks>
  156.     Public Sub CancelAsync()
  157.         If _isBusy Then
  158.             SetCancel()
  159.         End If
  160.     End Sub
  161.     ''' <summary>
  162.     ''' Récupère le type MIME d'un fichier
  163.     ''' </summary>
  164.     ''' <param name="szFileName">
  165.     ''' Nom du fichier dont on veut le type MIME
  166.     ''' </param>
  167.     ''' <param name="forceDatabase">
  168.     ''' true pour rechercher dans HKEY_CLASSES_ROOT\MIME\DataBase\Content Type (MIME -> extension),
  169.     ''' false pour rechercher
  170.     ''' dans HKEY_CLASSES_ROOT (extension -> MIME)
  171.     ''' </param>
  172.     ''' <returns>le type MIME ou null</returns>
  173.     Public Shared Function GetMIMEType(ByVal szFileName As String, ByVal forceDatabase As Boolean) As String
  174.         'type MIME renvoyé
  175.         Dim ret As String = Nothing
  176.         'extension du fichier avec "."
  177.         Dim szExt As String = Path.GetExtension(szFileName)
  178.         'valeur d'une valeur d'une clé de registre
  179.         Dim val As Object = Nothing
  180.         'si on veut lire dans HKEY_CLASSES_ROOT directement
  181.         If Not forceDatabase Then
  182.             'on essaie d'ouvrir la clé
  183.             Dim extKey As RegistryKey = Registry.ClassesRoot.OpenSubKey(szExt)
  184.             If extKey IsNot Nothing Then
  185.                 'il peut y avoir une valeur "Content Type" contenant le type MIME mais ce n'est pas obligatoire
  186.                 val = extKey.GetValue("Content Type" )
  187.                 extKey.Close()
  188.             End If
  189.         End If
  190.         'si on a déjà trouvé un type MIME et que l'on ne force pas la recherche dans HKEY_CLASSES_ROOT\MIME\DataBase\Content Type
  191.         If Not forceDatabase AndAlso val IsNot Nothing Then
  192.             Return val.ToString()
  193.         Else
  194.             'ouvre HKEY_CLASSES_ROOT\MIME\DataBase\Content Type
  195.             Dim contentTypeKey As RegistryKey = Registry.ClassesRoot.OpenSubKey("MIME\Database\Content Type" )
  196.             'parcourt toutes les sous clés (types MIME connus)
  197.             For Each subkey As String In contentTypeKey.GetSubKeyNames()
  198.                 'ouvre HKEY_CLASSES_ROOT\MIME\DataBase\Content Type\<type MIME>
  199.                 Dim contentTypeSubKey As RegistryKey = contentTypeKey.OpenSubKey(subkey)
  200.                 'récupère l'extension associée
  201.                 Dim ext As Object = contentTypeSubKey.GetValue("Extension" )
  202.                 'si ca correspond on a trouvé
  203.                 If ext IsNot Nothing AndAlso ext.ToString() = szExt Then
  204.                     ret = subkey
  205.                     Exit For
  206.                 End If
  207.                 contentTypeSubKey.Close()
  208.             Next
  209.             contentTypeKey.Close()
  210.         End If
  211.         Return ret
  212.     End Function
  213.     ''' <summary>
  214.     ''' Ajoute les entetes et les paires noms/Valeurs au fichier
  215.     ''' </summary>
  216.     ''' <param name="filepath">Chemin du fichier</param>
  217.     ''' <param name="fileFormName">Nom de champ fichier dans la webform</param>
  218.     ''' <param name="contenttype">Content type</param>
  219.     ''' <param name="querystring">Paires Nom/Valeur</param>
  220.     ''' <param name="boundary">Boundary</param>
  221.     ''' <param name="DATAS">structures des données à envoyer</param>
  222.     ''' <remarks></remarks>
  223.     Private Sub PrepareDatas3(ByVal filepath As String, ByVal fileFormName As String, ByVal contenttype As String, ByVal querystring As Specialized.NameValueCollection, ByVal boundary As String, ByRef DATAS As DatasToSend)
  224.         If (fileFormName Is Nothing) OrElse (fileFormName.Length = 0) Then
  225.             fileFormName = "file"
  226.         End If
  227.         If (contenttype Is Nothing) OrElse (contenttype.Length = 0) Then
  228.             contenttype = "application/octet-stream"
  229.         End If
  230.         Dim Startboundary As New System.Text.StringBuilder()
  231.         Startboundary.Append("--" )
  232.         Startboundary.Append(boundary)
  233.         Startboundary.Append(vbCrLf)
  234.         Startboundary.Append("Content-Disposition: form-data; name=""" )
  235.         Startboundary.Append(fileFormName)
  236.         Startboundary.Append("""; filename=""" )
  237.         Startboundary.Append(filepath)
  238.         Startboundary.Append("""" )
  239.         Startboundary.Append(vbCrLf)
  240.         Startboundary.Append("Content-Type: " )
  241.         Startboundary.Append(contenttype)
  242.         Startboundary.Append(vbCrLf)
  243.         Startboundary.Append(vbCrLf)
  244.         'ajoute les paires nom/valeurs
  245.         Dim Endboundary As New System.Text.StringBuilder()
  246.         If querystring IsNot Nothing Then
  247.             Endboundary.Append(vbCrLf)
  248.             For Each key As String In querystring.Keys
  249.                 Endboundary.Append("--" & boundary)
  250.                 Endboundary.Append(vbCrLf)
  251.                 Endboundary.Append("Content-Disposition: form-data; name=" & Chr(34) & key & Chr(34))
  252.                 Endboundary.Append(vbCrLf)
  253.                 Endboundary.Append(vbCrLf)
  254.                 Endboundary.Append(querystring.[Get](key))
  255.                 Endboundary.Append(vbCrLf)
  256.             Next
  257.         End If
  258.         Endboundary.Append("--" & boundary & "--" )
  259.         Endboundary.Append(vbCrLf)
  260.         Dim postHeader As String = Startboundary.ToString()
  261.         Dim postFooter As String = Endboundary.ToString
  262.         Dim postHeaderBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(postHeader)
  263.         Dim postFooterBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(postFooter)
  264.         ''''OUVERTURE DU FICHIER'''''
  265.         Dim fsRead As New FileStream(filepath, FileMode.Open, FileAccess.Read)
  266.         DATAS.FileStream = fsRead
  267.         DATAS.HeaderBytes = postHeaderBytes
  268.         DATAS.FooterBytes = postFooterBytes
  269.     End Sub
  270.     Public Sub UploadFileAsync(ByVal uri As Uri, ByVal inputfile As String, ByVal cookieCol As CookieCollection, Optional ByVal userToken As Object = Nothing)
  271.         SyncLock Me
  272.             CheckBusy()
  273.             Dim cbArgs() As Object = New Object() {uri, inputfile, cookieCol, userToken}
  274.             Dim cb As New WaitCallback(AddressOf cbMethod)
  275.             ThreadPool.QueueUserWorkItem(cb, cbArgs)
  276.         End SyncLock
  277.     End Sub
  278.     Private Sub cbMethod(ByVal innerState As Object)
  279.         Dim args() As Object = CType(innerState, Object())
  280.         Dim datas() As Byte
  281.         Dim url As Uri = CType(args(0), Uri)
  282.         Dim inputfile As String = CType(args(1), String)
  283.         Dim cookiecol As CookieCollection = CType(args(2), CookieCollection)
  284.         Dim usertoken As Object = args(3)
  285.         Try
  286.             datas = UploadFile(url, inputfile, cookiecol)
  287.             If _cancel Then
  288.                 '''CANCELLED'''
  289.                 SetCompleted()
  290.                 RaiseEvent UploadCompleted(New UploadCompletedArgs(Nothing, usertoken, Nothing, True))
  291.             Else
  292.                 '''NORMAL'''
  293.                 SetCompleted()
  294.                 RaiseEvent UploadCompleted(New UploadCompletedArgs(datas, usertoken, Nothing, False))
  295.             End If
  296.         Catch ex As Exception
  297.             '''ERROR'''
  298.             SetCompleted()
  299.             RaiseEvent UploadCompleted(New UploadCompletedArgs(Nothing, usertoken, ex, False))
  300.         End Try
  301.     End Sub
  302.     Public Function UploadFile(ByVal url As Uri, ByVal inputfile As String, ByVal cookieCol As CookieCollection) As Byte()
  303.         SetBusy()
  304.         Return UploadFileCore(url, inputfile, cookieCol)
  305.     End Function
  306.     Private Function UploadFileCore(ByVal url As Uri, ByVal inputfile As String, ByVal cookieCol As CookieCollection) As Byte()
  307.         _contentType = GetMIMEType(inputfile, False)
  308.         Dim DATAS As New DatasToSend
  309.         PrepareDatas3(inputfile, "", _contentType, _querystring, _boundary, DATAS)
  310.         Dim w As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
  311.         '''''HEADERZ'''''
  312.         w.Headers.Add(HttpRequestHeader.AcceptEncoding, _accept_encoding)
  313.         w.Headers.Add(HttpRequestHeader.AcceptLanguage, "fr" )
  314.         w.Headers.Add(HttpRequestHeader.AcceptCharset, _accept_charset)
  315.         w.Headers.Add(HttpRequestHeader.CacheControl, "no-cache" )
  316.         'w.Headers.Add(HttpRequestHeader.KeepAlive, "true" )
  317.         w.Headers.Add(HttpRequestHeader.KeepAlive, "300" )
  318.         w.ContentType = "multipart/form-data; boundary=" & _boundary
  319.         w.ProtocolVersion = HttpVersion.Version11
  320.         w.ServicePoint.Expect100Continue = False
  321.         w.ServicePoint.ConnectionLeaseTimeout = System.Threading.Timeout.Infinite
  322.         w.Timeout = System.Threading.Timeout.Infinite
  323.         w.Referer = _referer
  324.         w.UserAgent = _userAgent
  325.         w.Accept = _accept
  326.         '''''COOKIES'''''
  327.         ' w.CookieContainer = New CookieContainer()
  328.         ' w.CookieContainer.Add(cookieCol)
  329.         w.Headers.Add(HttpRequestHeader.Cookie, "age_check=1" )
  330.         ''''''METHODE''''''
  331.         w.Method = "POST"
  332.         '''''OPTIONS'''''
  333.         '      w.AutomaticDecompression = DecompressionMethods.GZip
  334.         w.AllowAutoRedirect = True
  335.         '      w.SendChunked = True
  336.         'Set content lenght
  337.         w.ContentLength = DATAS.Length
  338.         _contentLength = DATAS.Length
  339.         Dim totalDataRead As Integer
  340.         Try
  341.             'Ouvre la requete
  342.             Dim rsSender As Stream = w.GetRequestStream
  343.             Dim dataRead(BufferSize - 1) As Byte
  344.             Dim nbRead As Integer
  345.             'ENVOI DE L'HEARDER
  346.             rsSender.Write(DATAS.HeaderBytes, 0, DATAS.HeaderBytes.Length)
  347.             'ENVOI DU FICHIER
  348.             Do
  349.                 nbRead = DATAS.FileStream.Read(dataRead, 0, BufferSize)
  350.                 totalDataRead += nbRead
  351.                 rsSender.Write(dataRead, 0, nbRead)
  352.                 RaiseEvent UploadProgress(totalDataRead, _contentLength)
  353.             Loop Until nbRead < BufferSize Or _cancel = True
  354.             'Close FILE, WEBREQUEST
  355.             DATAS.FileStream.Close()
  356.             If _cancel Then
  357.                 w.Abort()
  358.                 Exit Function
  359.             End If
  360.             'ENVOI DU FOOTER
  361.             rsSender.Write(DATAS.FooterBytes, 0, DATAS.FooterBytes.Length)
  362.             rsSender.Close()
  363.             ''''Get RESPONSE''''
  364.             If Not _cancel Then
  365.                 Dim wResponse As WebResponse = w.GetResponse
  366.                 Dim rsResponce As Stream = (wResponse.GetResponseStream)
  367.                 Dim datasResp As New List(Of Byte)
  368.                 totalDataRead = 0
  369.                 nbRead = rsResponce.Read(dataRead, 0, BufferSize)
  370.                 While nbRead <> 0
  371.                     totalDataRead += nbRead
  372.                     ReDim Preserve dataRead(nbRead - 1)
  373.                     datasResp.AddRange(dataRead)
  374.                     ReDim Preserve dataRead(BufferSize - 1)
  375.                     nbRead = rsResponce.Read(dataRead, 0, BufferSize)
  376.                 End While
  377.                 'Close RESPONSE
  378.                 rsResponce.Close()
  379.                 Dim tabResp(datasResp.Count - 1) As Byte
  380.                 datasResp.CopyTo(tabResp)
  381.                 Return tabResp
  382.             End If
  383.             Return Nothing
  384.         Catch ex As Exception
  385.             DATAS.FileStream.Close()
  386.             Throw ex
  387.         End Try
  388.     End Function
  389. End Class
  390. Public Class UploadCompletedArgs
  391.     Private _rez() As Byte
  392.     Private _error As System.Exception
  393.     Private _cancelled As Boolean
  394.     Private _userstate As Object
  395.     Sub New(ByVal rez() As Byte, ByVal userstate As Object, ByVal err As Exception, ByVal cancelled As Boolean)
  396.         _userstate = userstate
  397.         _error = err
  398.         _cancelled = cancelled
  399.         _rez = rez
  400.     End Sub
  401.     Public ReadOnly Property Cancelled() As Boolean
  402.         Get
  403.             Return _cancelled
  404.         End Get
  405.     End Property
  406.     Public ReadOnly Property Result() As Byte()
  407.         Get
  408.             Return _rez
  409.         End Get
  410.     End Property
  411.     Public ReadOnly Property Errors() As Exception
  412.         Get
  413.             Return _error
  414.         End Get
  415.     End Property
  416.     Public ReadOnly Property UserState() As Object
  417.         Get
  418.             Return _userstate
  419.         End Get
  420.     End Property
  421. End Class


 
 
 
mais je n'arrive pas à faire executé aucune d'entre eux :(
 
 
 
merci de m'aider  
merci infiniment

mood
Publicité
Posté le 12-03-2009 à 15:32:21  profilanswer
 


Aller à :
Ajouter une réponse
  FORUM HardWare.fr
  Programmation
  C#/.NET managed

  automatiser l'envoi d'un fichier à un serveur jsp

 

Sujets relatifs
Fichier de link pour powerpcdossier, sous dossier, nombre de fichier, poids
Installer des programmes avec un fichier .bat[débutant] Récupération de valeur dans un fichier texte
Comment remplir une base avec un fichier texte?configurer ip fixe pour accéder à serveur cvs
Détecter l'effondrement d'un serveurRemplir un fichier pdf, avec des données xml, via php
Serveur en java et eclipse : Probléme de lancement[J2EE] un daemon sur un serveur j2EE ??
Plus de sujets relatifs à : automatiser l'envoi d'un fichier à un serveur jsp


Copyright © 1997-2022 Hardware.fr SARL (Signaler un contenu illicite / Données personnelles) / Groupe LDLC / Shop HFR