VB.NET将文件上传到网址

时间:2011-07-30 18:44:04

标签: vb.net file-upload

我正在编写一个需要将文件发送到Web脚本的VB.Net应用程序。

1. Dim uriString As New System.Uri("http://url/setup/image.php?title="+addNew_title.Text+"&price="+addNew_price.Text)
2. Dim myWebClient As New System.Net.WebClient()
3. Dim responseArray As Byte() = myWebClient.UploadFileAsync(uriString, OpenFileDialog1.FileName)
4. Dim response As String = System.Text.Encoding.ASCII.GetString(responseArray)

我提供的URI存在问题,它在第3行说“表达式不产生值”,其中使用了“uriString”。

当我使用myWebClient.UploadFile(String,String)时它会冻结发送,所以我发现,要继续执行代码我必须使用“UploadFileAsync”,但它不提供[String,String],但它需要[Uri,String]。

仅为了记录,我将放置代码截图: http://i.stack.imgur.com/CZKIk.png

我需要更改什么,因此代码有效,或者如果有其他方式上传此文件,请分享:)

1 个答案:

答案 0 :(得分:1)

UploadFileAsync不会返回任何值:http://msdn.microsoft.com/en-us/library/ms144232.aspx

您必须向UploadFileCompleted事件注册事件处理程序以获取响应或您的请求(这实际上是异步方法调用的重点)。

修改

很久以前,我上次编写VB.Net,但我认为以下内容应该是一个例子:

Public Class FileUploader

    Dim WithEvents client As New System.Net.WebClient()

    Public Sub StartUpload(ByVal targetUrl As String, ByVal filename As String)

        Dim uriString As New System.Uri(targetUrl)

        Me.client.UploadFileAsync(uriString, filename)

    End Sub

    Sub FileUploadCompleted(ByVal sender As Object, ByVal e As System.Net.UploadFileCompletedEventArgs) Handles client.UploadFileCompleted
        Dim response As String = System.Text.Encoding.ASCII.GetString(e.Result)

        ' further process your response string
    End Sub
End Class