Visualizzazione avanzamento durante caricamento dei dati
-
24-10-2019 - |
Domanda
Sto usando il seguente codice trova qui per caricare i file
Public Function UploadFile(ByVal oFile As FileInfo) As Boolean
Dim ftpRequest As FtpWebRequest
Dim ftpResponse As FtpWebResponse
Try
ftpRequest = CType(FtpWebRequest.Create(FTPSite + CurrentDirectory + oFile.Name), _
FtpWebRequest)
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile
ftpRequest.Proxy = Nothing
ftpRequest.UseBinary = True
ftpRequest.Credentials = New NetworkCredential(UserName, Password)
ftpRequest.KeepAlive = KeepAlive
ftpRequest.EnableSsl = UseSSL
If UseSSL Then ServicePointManager.ServerCertificateValidationCallback = _
New RemoteCertificateValidationCallback(AddressOf ValidateServerCertificate)
Dim fileContents(oFile.Length) As Byte
Using fr As FileStream = oFile.OpenRead
fr.Read(fileContents, 0, Convert.ToInt32(oFile.Length))
End Using
Using writer As Stream = ftpRequest.GetRequestStream
writer.Write(fileContents, 0, fileContents.Length)
End Using
ftpResponse = CType(ftpRequest.GetResponse, FtpWebResponse)
ftpResponse.Close()
ftpRequest = Nothing
Return True
Catch ex As WebException
Return False
End Try
End Function
Vorrei estenderla, così posso avere un avanzamento del caricamento troppo. Il problema è che non so da dove cominciare. Qual è la "logica" di visualizzare lo stato di avanzamento di upload?
"Split il file" in parti predefiniti e loro o che cosa caricare?
Nessuna soluzione corretta
Altri suggerimenti
È necessario eseguire la richiesta di upload su un thread in background per evitare di bloccare il thread UI. Il modo più semplice per farlo è usare la classe BackgroundWorker. E 'progettato specificamente per situazioni come questa.
Dim backgroundWorker As New System.ComponentModel.BackgroundWorker()
backgroundWorker.WorkerReportsProgress = True
backgroundWorker.WorkerSupportsCancellation = True
AddHandler backgroundWorker.DoWork, AddressOf Me.BackgroundFileDownload
AddHandler backgroundWorker.ProgressChanged, AddressOf Me.ProgressChanged
AddHandler backgroundWorker.RunWorkerCompleted, AddressOf Me.JobCompleted
Gli eventi ProgressChanged e RunWorkerCompleted vengono eseguite sul thread dell'interfaccia utente, e consentono di aggiornare la barra di avanzamento conseguenza con lo stato del download corrente. Cercheranno qualcosa di simile:
Protected Sub ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs)
progressBar.Value = e.ProgressPercentage
End Sub
DoWork viene chiamato su un thread in background, ed è dove si desidera chiamare in realtà la funzione UploadFile () che hai scritto. Per FtpWebRequest, si sta andando a voler ottenere prima la dimensione del file, poi come si caricano blocchi di dati, dividere quello che hai caricato finora dal formato completo del file per ottenere una percentuale di completamento. Qualcosa di simile
Worker.ReportProgress(Math.Round((_bytesUploaded / _fileSize) * 100))
Spero che questo aiuti.
Non sono sicuro se questo codice viene eseguito su un Windows Form o una pagina web, il che renderebbe la differenza nel modo in cui si mostra in realtà il progresso. Ma in entrambi i casi, che ci si vuole prima di questo metodo per segnalare il progresso da quanto esso sia.
Per fare ciò, la cosa migliore è di utilizzare gli eventi. Ecco cosa si avrebbe bisogno di aggiungere a questa classe e la funzione:
Per prima cosa una classe che detiene la percentuale:
Public Class ProgressEventArgs
Inherits System.EventArgs
Public Sub New(ByVal pPercentage As Decimal)
_Percentage = pPercentage
End Sub
Private _Percentage As Decimal
Public ReadOnly Property Percentage() As Decimal
Get
Return _Percentage
End Get
End Property
End Class
Avanti, ti consigliamo di aggiungere un evento alla classe che UploadFile appartiene a:
Public Event Progress(ByVal sender As Object, ByRef e As ProgressEventArgs)
Infine, nel, UploadFile, ti consigliamo di aumentare questo evento:
....
writer.Write(fileContents, 0, blockread)
RaiseEvent Progress(Me, new ProgressEventArgs(100 * block / blocks))
Next
....
Dove mai si sta chiamando questo da, è possibile ascoltare l'evento:
Private Sub HandleProgress(ByVal sender As Object, ByRef e As ProgressEventArgs)
'.... Update screen
End Sub
....
AddHandler YourUploadClass.Progress AddressOf HandleProgress