VB.net webrequest.uploadfile 中止错误

Posted

技术标签:

【中文标题】VB.net webrequest.uploadfile 中止错误【英文标题】:VB.net webrequest.uploadfile aborted error 【发布时间】:2018-05-12 13:09:43 【问题描述】:

我使用 webrequest 上传文件功能。但我对慢速网络中的大文件有错误。所以我想也许缓冲或其他东西对我有帮助

我的代码

Private Shared Function GetFileUploadResponse(ByVal fileToUpload As String, ByVal accessToken As String, ByVal uploadUrl As String) As UploadResponse
        Dim client = New WebClient()
        client.Headers.Add("Authorization", "OAuth " & accessToken)

        Dim responseBytes = client.UploadFile(uploadUrl, fileToUpload)

        Dim responseString = Encoding.UTF8.GetString(responseBytes)

        Dim response = JsonConvert.DeserializeObject(Of UploadResponse)(responseString)

        Return response



    End Function

当我尝试上传更大的 100 mb 文件时,错误中止。

我找到了这段代码,但这是用于 FTP 的。我使用普通的网络上传。我尝试修改我的代码,但每次尝试都会出错

Dim request As FtpWebRequest =
    WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip")
request.Credentials = New NetworkCredential("username", "password")
request.Method = WebRequestMethods.Ftp.UploadFile

Using fileStream As Stream = File.OpenRead("C:\local\path\file.zip"),
      ftpStream As Stream = request.GetRequestStream()
    Dim read As Integer
    Do
        Dim buffer() As Byte = New Byte(10240) 
        read = fileStream.Read(buffer, 0, buffer.Length)
        If read > 0 Then
            ftpStream.Write(buffer, 0, read)
            Console.WriteLine("Uploaded 0 bytes", fileStream.Position)
        End If
    Loop While read > 0
End Using

【问题讨论】:

很高兴您找到了解决方案!但请不要编辑您的问题以表明问题已解决。堆栈溢出不是那样工作的。而是将您的解决方案写为答案,并在时间允许时将其标记为已接受。谢谢! 【参考方案1】:

您必须在服务器端设置最大文件上传大小,显然您的设置为100mb。

On the server:
Open IIS Manager.
Select the website with your site name.
Double-click on "Request Filtering".
Click "Edit Feature Settings" on the right hand side of the page.
In the dialogue window that opens you can see the "Maximum allowed content length" field. The default is 30mb, apparently yours is set to 100mb Let us say we want our files to be up to 1GB, then we would need to put "1073741824" there.

【讨论】:

【参考方案2】:

找到解决方案。关于 webclient 超时的问题。这个 modifield webclient 很好用。

Public Class BigWebClient
    Inherits WebClient
    Protected Overrides Function GetWebRequest(ByVal address As System.Uri) As System.Net.WebRequest
        Dim x As WebRequest = MyBase.GetWebRequest(address)
        x.Timeout = 60 * 60 * 1000
        Return x
    End Function
End Class

【讨论】:

以上是关于VB.net webrequest.uploadfile 中止错误的主要内容,如果未能解决你的问题,请参考以下文章

VB.Net和C#.Net有啥差异?优缺点是啥?

VB.net中如何嵌套EXCEL?

vb.net 有没有++(增1)和--(减1)运算符?

VB.NET求帮忙!...

C# 和 VB.NET 的优缺点?

VB.net 和C#.net 各有啥优缺点