在开发自动化下载软件的过程中,意识到需要实现上传功能。本以为互联网上会有大量相关示例,但发现这方面的信息并不丰富。经过一番努力,最终找到了解决方案,并决定分享出来,以帮助有类似需求的人。
虽然访问和下载WebDAV服务器上的信息有多种方法,选择了使用HTTPS,并围绕此构建了一个演示程序。
如果熟悉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 port <> "" Then
Dim u As New Uri(url)
Dim host As String = u.Host
url = url.Replace(host, host & ":" & port)
End If
将要上传的文件名添加到URL的末尾。这会创建一个“目标”文件名。
url = url.TrimEnd("/") & "/" & IO.Path.GetFileName(fileToUpload)
为WebDAV服务器创建一个文件上传请求。
Dim userName As String = "UserName"
Dim password As String = "Password"
Dim request As HttpWebRequest = DirectCast(System.Net.HttpWebRequest.Create(url), HttpWebRequest)
request.Credentials = New NetworkCredential(userName, password)
request.Method = WebRequestMethods.Http.Put
request.ContentLength = fileLength
request.SendChunked = True
request.Headers.Add("Translate: f")
request.AllowWriteStreamBuffering = True
服务器给一个流后,就可以开始写入了。
Dim s As IO.Stream = request.GetRequestStream()
Dim fs As New IO.FileStream(fileToUpload, IO.FileMode.Open, IO.FileAccess.Read)
Dim byteTransferRate As Integer = 1024
Dim bytes(byteTransferRate - 1) As Byte
Dim bytesRead As Integer = 0
Dim totalBytesRead As Long = 0
Do
bytesRead = fs.Read(bytes, 0, bytes.Length)
If bytesRead > 0 Then
totalBytesRead += bytesRead
s.Write(bytes, 0, bytesRead)
End If
Loop While bytesRead > 0
s.Close()
s.Dispose()
s = Nothing
fs.Close()
fs.Dispose()
fs = Nothing
虽然已经将文件写入流中,但文件尚未上传。如果在没有继续的情况下退出,文件将不会被上传。
必须执行的最后一步是将数据发送到服务器。当请求服务器的响应时,实际上是在发送数据给服务器,并接收服务器的响应。如果不执行这一步,文件将不会被上传。
Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Dim code As HttpStatusCode = response.StatusCode
response.Close()
response = Nothing
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