如何在 VB.NET 中上传文件到 WebDAV 服务器
本文演示了如何在 VB.NET 中上传文件到(HTTPS)WebDAV 服务器。
引言
我公司最近将 FTP 站点迁移到了安全的 WebDAV 服务器(基于 Web 的分布式创作和版本控制)。 我被安排开发一些自动下载软件,这也导致了上传。 我认为在互联网上会有很多关于如何做到这一点的例子,但惊讶地发现我很难找到足够的信息。 因为我花了一段时间才拼凑起来,我想我会与可能具有类似需求的其他用户分享我的解决方案。
虽然可能有不同的方法来访问和下载 WebDAV 服务器中的信息,但我选择使用 HTTPS,并且围绕它构建了这个演示。
要了解如何从 WebDAV 服务器下载文件,请参阅我的文章 如何在 VB.NET 中从 WebDAV 服务器下载文件。
背景
如果您熟悉 HttpWebRequest
和 HttpWebResponse
,那么您应该会感到宾至如归。 常规服务器请求和 WebDAV 服务器请求之间的唯一区别是必须添加“Translate: f”标头,以及设置 SendChunks = True
和 AllowWriteStreamBuffering = True
。
如果您不熟悉将文件上传到 WebDAV 服务器,请继续关注。 我包含了一个演示,您可以下载并逐步了解它的工作原理。 该演示是使用 VS 2008、Visual Basic 和 .NET Framework 2.0 创建的。
使用代码
我们需要做的第一件事是获取文件的路径及其长度。
Dim fileToUpload As String = "c:\temp\transfer me.zip"
Dim fileLength As Long = My.Computer.FileSystem.GetFileInfo(fileToUpload).Length
接下来,我们需要获取 URL 和端口,如果提供了端口,则将它们组合起来。
Dim url As String = "https://someSecureTransferSite.com/directory"
Dim port As String = "443"
'If the port was provided, then insert it into the url.
If port <> "" Then
'Insert the port into the Url
'https://www.example.com:80/directory
Dim u As New Uri(url)
'Get the host (example: "www.example.com")
Dim host As String = u.Host
'Replace the host with the host:port
url = url.Replace(host, host & ":" & port)
End If
将我们正在上传的文件名添加到 URL 的末尾。 这会创建一个“目标”文件名。
url = url.TrimEnd("/"c) & "/" & IO.Path.GetFileName(fileToUpload)
为我们要上传的文件创建针对 WebDAV 服务器的请求。
Dim userName As String = "UserName"
Dim password As String = "Password"
'Create the request
Dim request As HttpWebRequest = _
DirectCast(System.Net.HttpWebRequest.Create(url), HttpWebRequest)
'Set the User Name and Password
request.Credentials = New NetworkCredential(userName, password)
'Let the server know we want to "put" a file on it
request.Method = WebRequestMethods.Http.Put
'Set the length of the content (file) we are sending
request.ContentLength = fileLength
'*** This is required for our WebDav server ***
request.SendChunked = True
request.Headers.Add("Translate: f")
request.AllowWriteStreamBuffering = True
'Send the request to the server, and get the
' server's (file) Stream in return.
Dim s As IO.Stream = request.GetRequestStream()
在服务器给了我们一个流之后,我们就可以开始写入它了。
注意:数据实际上并没有被发送到服务器,而是写入内存中的流。 当从服务器请求响应时,数据实际上是在下面发送的。
'Open the file so we can read the data from it
Dim fs As New IO.FileStream(fileToUpload, IO.FileMode.Open, _
IO.FileAccess.Read)
'Create the buffer for storing the bytes read from the file
Dim byteTransferRate As Integer = 1024
Dim bytes(byteTransferRate - 1) As Byte
Dim bytesRead As Integer = 0
Dim totalBytesRead As Long = 0
'Read from the file and write it to the server's stream.
Do
'Read from the file
bytesRead = fs.Read(bytes, 0, bytes.Length)
If bytesRead > 0 Then
totalBytesRead += bytesRead
'Write to stream
s.Write(bytes, 0, bytesRead)
End If
Loop While bytesRead > 0
'Close the server stream
s.Close()
s.Dispose()
s = Nothing
'Close the file
fs.Close()
fs.Dispose()
fs = Nothing
现在,虽然我们已经完成了将文件写入流的操作,但该文件尚未上传。 如果我们在这里退出而不继续,则该文件将不会上传。
我们必须执行的最后一步是将数据发送到服务器。
- 当我们从服务器请求响应时,我们实际上是将数据发送到服务器,并接收服务器的响应作为回报。
- 如果我们不执行此步骤,则该文件将不会上传。
Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
最后,在我们上传文件后,执行一些验证以确保一切正常。
'Get the StatusCode from the server's Response
Dim code As HttpStatusCode = response.StatusCode
'Close the response
response.Close()
response = Nothing
'Validate the uploaded file.
' Check the totalBytesRead and the fileLength: Both must be an exact match.
'
' Check the StatusCode from the server and make sure the file was "Created"
' Note: There are many different possible status codes. You can choose
' which ones you want to test for by looking at the "HttpStatusCode" enumerator.
If totalBytesRead = fileLength AndAlso _
code = HttpStatusCode.Created Then
MessageBox.Show("The file has uploaded successfully!", "Upload Complete", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show("The file did not upload successfully.", _
"Upload Failed", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
结论
我希望这个演示能帮助你!
请记住查看我的另一篇文章:如何在 VB.NET 中从 WebDAV 服务器下载文件。