如何在VB.Net中使用WebClient.UploadFileAsync发布自定义标头

时间:2015-03-04 09:44:13

标签: vb.net asynchronous file-upload webclient

我的代码中有一个文件上传脚本,需要在上传时发布身份验证密钥标头。但是,它似乎没有像我预期的那样工作。到目前为止,这是我的代码:

Private Sub uploadFile()

    Dim address As String = "http://localhost/stripe/upload.php"

    Dim client As WebClient = New WebClient()
    Dim uri As Uri = New Uri(address)

    AddHandler client.UploadFileCompleted, AddressOf UploadFileCompleted
    AddHandler client.UploadProgressChanged, AddressOf UploadProgressCallback

    client.Headers.Set("authKey", login.authKey)
    client.UploadFileAsync(uri, "POST", uploadFileName)

End Sub

Private Sub UploadProgressCallback(ByVal sender As Object, ByVal e As UploadProgressChangedEventArgs)
    ProgressBar1.Value = e.ProgressPercentage
    Label3.Text = String.Format("{0} / {1} kB", Math.Round(e.BytesSent / 1024), Math.Round(e.TotalBytesToSend / 1024))
    Label2.Text = String.Format("{0}%", e.ProgressPercentage)
    Application.DoEvents()
End Sub

Private Sub UploadFileCompleted(ByVal sender As Object, ByVal e As UploadFileCompletedEventArgs)
    Dim response As String = System.Text.Encoding.ASCII.GetString(e.Result)
    Console.WriteLine(response)
End Sub

当我运行这段代码时:没有任何反应。输出控制台中没有换行符或任何东西。就像代码从未到达UploadFileCompleted Sub。它似乎无法到达UploadProgressCallback,因为进度条和相关标签永远不会更新。

当我尝试注释client.Headers.Set("authKey", login.authKey)行时:文件似乎上传,但完成后:我收到403 Forbidden消息,因为我没有authKey标题集。

我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

我发现了我的问题。问题是由login.authKey无法访问调用它的线程引起的。由于程序是多线程的:我必须确保线程可以访问它。当我可以访问时:该功能按预期工作。

希望这有助于我身后的其他人。 :)