Hello!
I'm trying to upload a file to a self-made website using php.
I can
upload a file using a html file on the server but I wanted to do it
with VB.net app.
This is what I already found (and edited) on the net.
When I want to run this code, I receive an
error in this line:
Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Normally the last 10 lines of code works ok when I wanted to upload normal data (e.g. a name or other string,...).
What's wrong? My header? Or the way I want to write it to the stream, ...?
Function SendFile(ByVal filepath As String, ByVal feedbackUrl As String)
Dim boundery As String = IO.Path.GetRandomFileName
Dim header As New System.Text.StringBuilder()
header.AppendLine("--" & boundery)
header.Append("Content-Disposition: form-data; name=""userfile"";")
header.AppendFormat("filename=""{0}""", IO.Path.GetFileName(filepath))
header.AppendLine()
header.AppendLine("Content-Type: application/octet-stream")
header.AppendLine()
Dim headerbytes() As Byte = System.Text.Encoding.UTF8.GetBytes(header.ToString)
Dim endboundarybytes() As Byte = System.Text.Encoding.ASCII.GetBytes(vbNewLine & "--" & boundery & "--" & vbNewLine)
Dim request As HttpWebRequest = DirectCast(WebRequest.Create(feedbackUrl), HttpWebRequest)
request.UserAgent = "My Program Agent"
request.Method = "POST"
request.ContentType = "multipart/form-data; boundary=" & boundery
request.ContentLength = headerbytes.Length + New FileInfo(filepath).Length + endboundarybytes.Length
Dim filebytes() As Byte = My.Computer.FileSystem.ReadAllBytes(filepath)
Dim requestStream As System.IO.Stream = request.GetRequestStream()
requestStream.Write(headerbytes, 0, headerbytes.Length)
requestStream.Write(filebytes, 0, filebytes.Length)
requestStream.Write(endboundarybytes, 0, endboundarybytes.Length)
requestStream.Close()
Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Dim streamgt As System.IO.Stream = response.GetResponseStream()
Dim length As Int64 = 100000
Dim txt(length) As Byte
streamgt.Read(txt, 0, length)
streamgt.Close()
streamgt.Dispose()
Return txt
End Function