Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.net HTTP post, count bytes sent asynchronously for progress bar

Tags:

vb.net

Currently I have the following function:

Private Function uploadFile(ByVal fileName As String)
    Dim data() As Byte = IO.File.ReadAllBytes(fileName)
    Dim base64String = System.Convert.ToBase64String(data)
    Dim uploadURL As String = "http://192.168.0.7/upload.php"
    Try
        Using client As New Net.WebClient
            Dim reqParm As New Specialized.NameValueCollection
            reqParm.Add("body", base64String)
            Dim responsebytes = client.UploadValues(uploadURL, "POST", reqParm)
            Dim responsebody = (New Text.UTF8Encoding).GetString(responsebytes)
        End Using
    Catch ex As System.Net.WebException
        MsgBox(ex.Message)
    Finally
            '
    End Try
End Function

This will send the file contents in an http request as a base64 encoded string. I'd like to add a progressbar so the progress can be monitored. With Java I could implement this by incrementing a bytes sent counter as I add one byte at a time to the output stream for the request. Do I have that same option with VB.net, or maybe another option? Thanks for any thoughts

like image 213
RandomUser Avatar asked Mar 24 '26 21:03

RandomUser


1 Answers

You can use UploadValuesAsync and listen to the event handlers UploadProgressChanged and UploadValuesCompleted.

Sample code:

Private Sub UploadProgressChanged(ByVal sender As Object, ByVal e As Net.UploadProgressChangedEventArgs)
    ' The progress is updated
    ProgressBar1.Value = e.ProgressPercentage
End Sub

Private Sub UploadValuesCompleted(ByVal sender As Object, ByVal e As Net.UploadValuesCompletedEventArgs)
    Dim responsebytes = e.Result
    Dim responsebody = (New System.Text.UTF8Encoding).GetString(responsebytes)
    ' Do whatever you want
    MsgBox(responsebody)
End Sub

Private Function uploadFile(ByVal fileName As String) As Boolean
    Dim data() As Byte = IO.File.ReadAllBytes(fileName)
    Dim base64String = System.Convert.ToBase64String(data)
    Dim uploadURL As String = "http://192.168.0.7/upload.php"
    Try
        Using client As New Net.WebClient
            Dim reqParm As New Specialized.NameValueCollection
            reqParm.Add("body", base64String)
            AddHandler client.UploadProgressChanged, AddressOf UploadProgressChanged
            AddHandler client.UploadValuesCompleted, AddressOf UploadValuesCompleted
            client.UploadValuesAsync(New System.Uri(uploadURL), "POST", reqParm)
        End Using
    Catch ex As System.Net.WebException
        MsgBox(ex.Message)
    Finally
        '
    End Try
    Return True
End Function
like image 131
Alvin Wong Avatar answered Mar 26 '26 14:03

Alvin Wong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!