我知道,是旧的.. 但这里是我的解决方案工作:
Private Sub HttpUploadFile(
ByVal uri As String,
ByVal filePath As String,
ByVal fileParameterName As String,
ByVal contentType As String)
Dim myFile As New FileInfo(filePath)
Dim sizeInBytes As Long = myFile.Length
Dim boundary As String = "---------------------------" & DateTime.Now.Ticks.ToString("x")
Dim newLine As String = System.Environment.NewLine
Dim boundaryBytes As Byte() = Encoding.ASCII.GetBytes(newLine & "--" & boundary & newLine)
Dim request As Net.HttpWebRequest = Net.WebRequest.Create(uri)
request.ContentType = "multipart/form-data; boundary=" & boundary
request.Method = "POST"
request.KeepAlive = True
'request.Credentials = Net.CredentialCache.DefaultCredentials
Using requestStream As IO.Stream = request.GetRequestStream()
Dim formDataTemplate As String = "Content-Disposition: form-data; name=""{0}""{1}{1}{2}"
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length)
Dim headerTemplate As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}""{2}Content-Type: {3};"
Dim header As String = String.Format(headerTemplate, fileParameterName, filePath, newLine, contentType)
header = header & vbNewLine & "Content-Length: " & sizeInBytes.ToString & vbNewLine
header = header & "Expect: 100-continue" & vbNewLine & vbNewLine
'MsgBox(header)
Debug.Print(header)
Dim headerBytes As Byte() = Encoding.UTF8.GetBytes(header)
requestStream.Write(headerBytes, 0, header.Length)
Using fileStream As New IO.FileStream(filePath, IO.FileMode.Open, IO.FileAccess.Read)
Dim buffer(4096) As Byte
Dim bytesRead As Int32 = fileStream.Read(buffer, 0, buffer.Length)
Do While (bytesRead > 0)
requestStream.Write(buffer, 0, bytesRead)
bytesRead = fileStream.Read(buffer, 0, buffer.Length)
Loop
End Using
Dim trailer As Byte() = Encoding.ASCII.GetBytes(newLine & "--" + boundary + "--" & newLine)
requestStream.Write(trailer, 0, trailer.Length)
requestStream.Close()
End Using
Dim response As Net.WebResponse = Nothing
Try
response = request.GetResponse()
Using responseStream As IO.Stream = response.GetResponseStream()
Using responseReader As New IO.StreamReader(responseStream)
Dim responseText = responseReader.ReadToEnd()
Debug.Print(responseText)
End Using
End Using
Catch exception As Net.WebException
response = exception.Response
If (response IsNot Nothing) Then
Using reader As New IO.StreamReader(response.GetResponseStream())
Dim responseText = reader.ReadToEnd()
Diagnostics.Debug.Write(responseText)
End Using
response.Close()
End If
Finally
request = Nothing
End Try
End Sub
使用:
HttpUploadFile("https://www.yousite.com/ws/upload.php?option1=sss&options2=12121", FULL_FILE_NAME_PATH_IN_YOUR_PC, "files", "multipart/form-data")
我在一个我不记得的网站上复制了一些代码。我只使用了这 2 行代码:
header = header & vbNewLine & "Content-Length: " & sizeInBytes.ToString & vbNewLine header = header & vbNewLine & "Expect: 100-continue" & vbNewLine
希望有所帮助。