VB.NET upload file to a web url
i am writing a VB.Net app that has need to send a file to web script.
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)
There is a problem with URI that i give, it says "Expression does not produce a value" on line 3. where "uriString" used.
When i used myWebClient.UploadFile(String,String) it freeze on sending, so i found out, that to continue code execution i have to use "UploadFileAsync", but it does not provide [String,String], but it requires [Uri,String].
Just for the record, i will put a screenshot of code: http://i.stack.imgur.com/CZKIk.png
What开发者_Go百科 do i have to change, so code is valid, or if there is another way to upload this file, please share :)
UploadFileAsync does not return any value: http://msdn.microsoft.com/en-us/library/ms144232.aspx
You have to register an event handler to the UploadFileCompleted event to get the response or your request (that's actually the point of asynchronous method calls).
Edit
It is quite some time ago that I last programmed VB.Net, but I think the following should work as an example:
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
精彩评论