Displaying progress while uploading data
-
24-10-2019 - |
Pergunta
I am using the following code located here to upload files
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
I would like to extend it, so i can have an upload progress too. The problem is that i do not know from where to start. What is the "logic" of displaying the upload progress?
"Split the file" in predefined parts and upload them or what?
Nenhuma solução correta
Outras dicas
You need to execute the upload request on a background thread to avoid blocking the UI thread. The easiest way to do this is using the BackgroundWorker class. It's designed specifically for situations like this.
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
The events ProgressChanged and RunWorkerCompleted are run on the UI thread, and allow you to update the progress bar accordingly with the current download's status. They'll look something like this:
Protected Sub ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs)
progressBar.Value = e.ProgressPercentage
End Sub
DoWork is called on a background thread, and is where you want to actually call the UploadFile() function you've written. For FtpWebRequest, you're going to want to first get the file's size, then as you upload blocks of data, divide what you've uploaded so far by the file's full size to get a percentage complete. Something like
Worker.ReportProgress(Math.Round((_bytesUploaded / _fileSize) * 100))
Hope this helps.
I'm not sure if this code is running on a windows form or web page, which would make a difference in how you actually show the progress. But either way, you'd first want this method to report the progress on how far it is.
To do so, the best bet is to use events. Here is what you would need to add to this class and function:
First a class holding the Percentage:
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
Next, you'll want to add an event to the class that UpLoadFile belongs to:
Public Event Progress(ByVal sender As Object, ByRef e As ProgressEventArgs)
Finally in, UpLoadFile, you'll want to raise this event:
....
writer.Write(fileContents, 0, blockread)
RaiseEvent Progress(Me, new ProgressEventArgs(100 * block / blocks))
Next
....
Where ever you are calling this from, you can listen for the event:
Private Sub HandleProgress(ByVal sender As Object, ByRef e As ProgressEventArgs)
'.... Update screen
End Sub
....
AddHandler YourUploadClass.Progress AddressOf HandleProgress