|
Trouver une ressource
Vous ne trouvez pas de réponse à votre problème ? Alors posez la question dans le forum. Souvenez-vous qu'il n'y a jamais de question bête, mais rester dans l'ignorance parce que l'on n'ose pas poser une question, ça c'est une erreur !
[.NET2] CLASSE DE TÉLÉCHARGEMENT HTTP AVEC GESTION DE RESUME, PROGRESSION, AUTHENTIFICATION, PROXY, ÉVENEMENT THREADS-SAFE...
Information sur la source
Description
Hello le monde. Voila une évolution de la classe que j'avais ecrit pour vb2002/2003 (présente sur le site). Celle ci gère (heuresement) tout ce que fesait l'ancienne : resume, progression, proxy Et les nouveautés : _C'est maintenant une "vraie" classe _Gestion de l'authentification type htaccess _Gestion événement permettant des accés "thread-safe" aux controles des forms (le problème ne se posait pas en 2003, du moins aucunes exception n'était levée) _Gestion d'erreures (simplistes, mais présente) _Gestion des fichiers dont la taille n'est pas renvoyé par le header Pourquoi n'ai je pas simplement fait une mise à jour du code exisant? _Le sample accompagnant la classe a du être modifié, l'ancien n'est pas compatible avec cette nouvelle classe _Les backgroundworker utilisé pour les renvoit d'évenement n'existent pas avant .Net 2.0 _La classe a été completement réecrite proprement _L'ancienne classe marche très bien sous vb2002/2003 Cependant, si un admin juge qu'une simple mise à jour aurait suffit, la suppression de cette source ne me vexera pas ^^
Source
- Option Strict On
- Imports System.Net
-
- Public Class HBDownloader2005
-
- #Region "évenements"
- Public Event download_Started(ByVal sender As Object, ByVal totalfilelen As Long, ByVal resumepos As Long, ByVal TimeTickStart As Long)
- Public Event download_Progress(ByVal sender As Object, ByVal CurPosition As Long, ByVal CurPercentage As Integer)
- Public Event download_Ended(ByVal sender As Object, ByVal EndPosition As Long, ByVal CurPercentage As Integer)
- Public Event download_Error(ByVal sender As Object, ByVal ex As Exception)
- #End Region
-
- #Region "attributs"
- Private b As Boolean
- Private WithEvents bgw As System.ComponentModel.BackgroundWorker
- Private BufSize As Integer = 32768
- Private BytesArr(BufSize) As Byte
- Private CurPos As Long
- Private FileLength As Long
- Private Hwebrequest As HttpWebRequest
- Private IsResume As Boolean
- Private ReadStream As IO.Stream
- Private ResumePos As Long
- Private StartTime As DateTime
- Private TargetPath As String
- Private FileUrl As String
- #End Region
-
- #Region "proprietés"
- Public Property BufferSize() As Integer
- Get
- Return BufSize
- End Get
- Set(ByVal value As Integer)
- BufSize = value
- Array.Resize(BytesArr, BufSize)
- End Set
- End Property
- Public ReadOnly Property Start_Time() As Date
- Get
- Return StartTime
- End Get
- End Property
-
- Public ReadOnly Property Start_Tick() As Long
- Get
- Return StartTime.Ticks
- End Get
- End Property
- #End Region
-
- #Region "méthodes"
- Public Sub Start(ByVal pathstr As String, ByVal strurl As String, ByVal bresume As Boolean)
- Start(pathstr, strurl, IsResume, "", "", Nothing, Nothing)
- End Sub
-
- Public Sub Start(ByVal pathstr As String, ByVal strurl As String, ByVal bresume As Boolean, ByVal login As String, ByVal pass As String)
- Start(pathstr, strurl, IsResume, login, pass, Nothing, Nothing)
- End Sub
-
- Public Sub Start(ByVal pathstr As String, ByVal strurl As String, ByVal bresume As Boolean, ByVal proxy As String, ByVal proxyport As Integer)
- Start(pathstr, strurl, IsResume, "", "", proxy, proxyport)
- End Sub
-
- Public Sub Start(ByVal pathstr As String, ByVal strurl As String, ByVal bresume As Boolean, ByVal login As String, ByVal pass As String, ByVal proxy As String, ByVal proxyport As Integer)
- b = True
- IsResume = bresume
- StartTime = Now
- TargetPath = pathstr
- FileUrl = strurl
- Open_request(strurl, pathstr, login, pass, proxy, proxyport)
- End Sub
-
- Public Sub Stop_Download()
- b = False
- End Sub
-
- Private Sub Open_request(ByVal fileurl As String, ByVal filepath As String, ByVal login As String, ByVal pass As String, ByVal proxy As String, ByVal proxyport As Integer)
- Try
- If proxy <> "" Then
- Dim hproxy As WebProxy
- hproxy = New WebProxy(proxy, proxyport)
- WebRequest.DefaultWebProxy = hproxy
- End If
- Hwebrequest = CType(System.Net.HttpWebRequest.Create(fileurl), System.Net.HttpWebRequest)
- If login <> "" Then
- Dim hcredential As New System.Net.NetworkCredential(login, pass)
- Hwebrequest.Credentials = hcredential
- End If
- If IsResume = True Then
- ResumePos = FileLen(filepath)
- CurPos = ResumePos
- Hwebrequest.AddRange(CInt(CurPos))
- End If
- Dim hwebresponse As System.Net.HttpWebResponse = CType(Hwebrequest.GetResponse, System.Net.HttpWebResponse)
- ReadStream = hwebresponse.GetResponseStream
- FileLength = hwebresponse.ContentLength + CurPos
- StartTime = Now
- RaiseEvent download_Started(Me, FileLength, ResumePos, StartTime.Ticks)
- bgw = New System.ComponentModel.BackgroundWorker
- bgw.WorkerReportsProgress = True
- bgw.RunWorkerAsync()
- Catch ex As Exception
- RaiseEvent download_Error(Me, ex)
- End Try
- End Sub
-
- Private Function Get_Percentage(ByVal tmppos As Long, ByVal totallen As Long) As Integer
- Dim tmpres As Long
- If totallen > 0 Then
- tmpres = CLng((tmppos / totallen) * 100)
- Else 'si la taille du fichier n'était pas connue
- tmpres = -1
- End If
- Return CInt(tmpres)
- End Function
-
- Private Sub Get_file(ByVal filepath As String)
- Try
- Dim tmplen As Integer
- b = True
- Do
- tmplen = ReadStream.Read(BytesArr, 0, BufSize)
- CurPos += tmplen
- Dim filesave As New IO.FileStream(filepath, IO.FileMode.Append, IO.FileAccess.Write)
- filesave.Write(BytesArr, 0, tmplen)
- filesave.Close()
- bgw.ReportProgress(Get_Percentage(CurPos, FileLength))
- System.Threading.Thread.Sleep(1)
- Loop While (tmplen > 0 And b = True)
- b = False
- ReadStream.Close()
- Catch ex As Exception
- RaiseEvent download_Error(Me, ex)
- End Try
- End Sub
-
- Private Sub bgw_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgw.DoWork
- Get_file(TargetPath)
- End Sub
-
- Private Sub bgw_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bgw.ProgressChanged
- RaiseEvent download_Progress(Me, CurPos, e.ProgressPercentage)
- End Sub
-
- Private Sub bgw_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgw.RunWorkerCompleted
- RaiseEvent download_Ended(Me, CurPos, Get_Percentage(CurPos, FileLength))
- End Sub
- #End Region
-
- End Class
Option Strict On
Imports System.Net
Public Class HBDownloader2005
#Region "évenements"
Public Event download_Started(ByVal sender As Object, ByVal totalfilelen As Long, ByVal resumepos As Long, ByVal TimeTickStart As Long)
Public Event download_Progress(ByVal sender As Object, ByVal CurPosition As Long, ByVal CurPercentage As Integer)
Public Event download_Ended(ByVal sender As Object, ByVal EndPosition As Long, ByVal CurPercentage As Integer)
Public Event download_Error(ByVal sender As Object, ByVal ex As Exception)
#End Region
#Region "attributs"
Private b As Boolean
Private WithEvents bgw As System.ComponentModel.BackgroundWorker
Private BufSize As Integer = 32768
Private BytesArr(BufSize) As Byte
Private CurPos As Long
Private FileLength As Long
Private Hwebrequest As HttpWebRequest
Private IsResume As Boolean
Private ReadStream As IO.Stream
Private ResumePos As Long
Private StartTime As DateTime
Private TargetPath As String
Private FileUrl As String
#End Region
#Region "proprietés"
Public Property BufferSize() As Integer
Get
Return BufSize
End Get
Set(ByVal value As Integer)
BufSize = value
Array.Resize(BytesArr, BufSize)
End Set
End Property
Public ReadOnly Property Start_Time() As Date
Get
Return StartTime
End Get
End Property
Public ReadOnly Property Start_Tick() As Long
Get
Return StartTime.Ticks
End Get
End Property
#End Region
#Region "méthodes"
Public Sub Start(ByVal pathstr As String, ByVal strurl As String, ByVal bresume As Boolean)
Start(pathstr, strurl, IsResume, "", "", Nothing, Nothing)
End Sub
Public Sub Start(ByVal pathstr As String, ByVal strurl As String, ByVal bresume As Boolean, ByVal login As String, ByVal pass As String)
Start(pathstr, strurl, IsResume, login, pass, Nothing, Nothing)
End Sub
Public Sub Start(ByVal pathstr As String, ByVal strurl As String, ByVal bresume As Boolean, ByVal proxy As String, ByVal proxyport As Integer)
Start(pathstr, strurl, IsResume, "", "", proxy, proxyport)
End Sub
Public Sub Start(ByVal pathstr As String, ByVal strurl As String, ByVal bresume As Boolean, ByVal login As String, ByVal pass As String, ByVal proxy As String, ByVal proxyport As Integer)
b = True
IsResume = bresume
StartTime = Now
TargetPath = pathstr
FileUrl = strurl
Open_request(strurl, pathstr, login, pass, proxy, proxyport)
End Sub
Public Sub Stop_Download()
b = False
End Sub
Private Sub Open_request(ByVal fileurl As String, ByVal filepath As String, ByVal login As String, ByVal pass As String, ByVal proxy As String, ByVal proxyport As Integer)
Try
If proxy <> "" Then
Dim hproxy As WebProxy
hproxy = New WebProxy(proxy, proxyport)
WebRequest.DefaultWebProxy = hproxy
End If
Hwebrequest = CType(System.Net.HttpWebRequest.Create(fileurl), System.Net.HttpWebRequest)
If login <> "" Then
Dim hcredential As New System.Net.NetworkCredential(login, pass)
Hwebrequest.Credentials = hcredential
End If
If IsResume = True Then
ResumePos = FileLen(filepath)
CurPos = ResumePos
Hwebrequest.AddRange(CInt(CurPos))
End If
Dim hwebresponse As System.Net.HttpWebResponse = CType(Hwebrequest.GetResponse, System.Net.HttpWebResponse)
ReadStream = hwebresponse.GetResponseStream
FileLength = hwebresponse.ContentLength + CurPos
StartTime = Now
RaiseEvent download_Started(Me, FileLength, ResumePos, StartTime.Ticks)
bgw = New System.ComponentModel.BackgroundWorker
bgw.WorkerReportsProgress = True
bgw.RunWorkerAsync()
Catch ex As Exception
RaiseEvent download_Error(Me, ex)
End Try
End Sub
Private Function Get_Percentage(ByVal tmppos As Long, ByVal totallen As Long) As Integer
Dim tmpres As Long
If totallen > 0 Then
tmpres = CLng((tmppos / totallen) * 100)
Else 'si la taille du fichier n'était pas connue
tmpres = -1
End If
Return CInt(tmpres)
End Function
Private Sub Get_file(ByVal filepath As String)
Try
Dim tmplen As Integer
b = True
Do
tmplen = ReadStream.Read(BytesArr, 0, BufSize)
CurPos += tmplen
Dim filesave As New IO.FileStream(filepath, IO.FileMode.Append, IO.FileAccess.Write)
filesave.Write(BytesArr, 0, tmplen)
filesave.Close()
bgw.ReportProgress(Get_Percentage(CurPos, FileLength))
System.Threading.Thread.Sleep(1)
Loop While (tmplen > 0 And b = True)
b = False
ReadStream.Close()
Catch ex As Exception
RaiseEvent download_Error(Me, ex)
End Try
End Sub
Private Sub bgw_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgw.DoWork
Get_file(TargetPath)
End Sub
Private Sub bgw_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bgw.ProgressChanged
RaiseEvent download_Progress(Me, CurPos, e.ProgressPercentage)
End Sub
Private Sub bgw_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgw.RunWorkerCompleted
RaiseEvent download_Ended(Me, CurPos, Get_Percentage(CurPos, FileLength))
End Sub
#End Region
End Class
Conclusion
Historique
- 14 mars 2007 15:39:48 :
- premier bug ^^' ...
- 15 mars 2007 01:52:56 :
- _le fait de telecharger un fichier dont la taille n'est pas connue ne lève plus d'erreur
_adaptation du sample à ce genre de cas
Sources du même auteur
Sources de la même categorie
Sources en rapport avec celle ci
Commentaires et avis
Discussions en rapport avec ce code source dans le forum
WESGEN: critiquez-moi SVP [ par coucout ]
Bonjour,J'ai réalisé un logiciel sous Access 97 baptisé WESGEN dont le but est de générer des applications de gestion de BDD. Vous pouvez aller le tél
Download, téléchargement, HTTP [ par DavidT ]
Bien sur que Winsock.ocx peut effectuer ces actions mais je cherche surtout un API qui me permettrait de télécharger de gros fichiers en Web (HTTP) et
API => Download HTTP + Proxy + username +Password <CASSE TÊTE !!! [ par DavidT ]
Bonjour, Y en a marre du INET qui marche une fois sur deux et du Winsock pas très sur !Bon, j'essaye de m'accrocher aux API, et la c'est le casse tête
AIDEZ MOI c simplement un download sur ftp ou http [ par gavirtual ]
Si tu li se message je te remecialors que je t'explique mon problèmeje voudrais avoir une source pour télécharger un .exe sur un server ftp ou http et
Download avec Inet en http ?? [ par JcDuss ]
Peut on recuperer une image avec le controle inet ?Peut etre avec le ByteArray, mais je ne sais pas l'utiliser.Et j'aimerais eviter d'utiliser winsock
Télécharger un fichier sur un HTTP/FTP [ par Jielde ]
Voilla, comment faire pour trouvé la taille d'un fichier sur un HTTP/FTP (de grosse capacité >2mo) puis de le télécharger avec la progression ? et
Télécharger fichier avec progressbar en HTTP [ par z980x ]
Salut !Bon, j'ai cherché sur le site, mais soit ca ne marchait pas, soit je ne comprenais rien tellement c'était compliqué...J'ai un fichier sur inter
télécharger un fichier exe sur http et/ou sur ftp [ par spliceh ]
bonjour, je cherche un code pour télécharger un fichier exe sur internet et le stocker sur ma machine. j'ai cru voir dans le forum winsock et inet mai
Télécharger un fichier par http via inet [ par Florian29 ]
Salut !J'aimerai pouvoir télécharger un fichier (zip) par inet à partir d'une adresse HTTP (et non FTP)...Quelqun aurait-il une solution ou encore mie
download [ par chasseurdedemon ]
bonjour je débute en vb6 et j'ai réussi a créer un explorateur (aprés de dure heur de recherche et de l'abeur ) et il marche
|
Téléchargements
Logiciels à télécharger sur le même thème :
|