开发者

WebClient.UploadFile failed with "The request was aborted: The request was canceled."

I am trying to upload a file to a HTTP URL with WebClient.UploadFile. For small file such as 1M, 2M, the uploading is successful. But for a big file such as 12M, I got this exception:

The request was aborted: The request was canceled.

Has anyone met this problem before and could y开发者_JAVA百科ou share the solution?

Some info:

  • The server is using ASP.NET 3.5.
  • The HTTP method I used in uploading is "PUT".


Here is the solution referred to in smwikipedia's answer. I've added the ability to disable write stream buffering, which can help with out of memory exceptions.

public class ExtendedWebClient : WebClient
{
    public int Timeout { get; set; }
    public new bool AllowWriteStreamBuffering { get; set; }

    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address);
        if (request != null)
        {
            request.Timeout = Timeout;
            var httpRequest = request as HttpWebRequest;
            if (httpRequest != null)
            {
                httpRequest.AllowWriteStreamBuffering = AllowWriteStreamBuffering;
            }
        }
        return request;
    }

    public ExtendedWebClient()
    {
        Timeout = 100000; // the standard HTTP Request Timeout default
    }
}

Usage:

var webClient = new ExtendedWebClient();
webClient.Timeout = Timeout.Infinite;
webClient.AllowWriteStreamBuffering = false;
webClient.UploadFile(url, filePath);


I solved it according to here: Extend the timeout value of WebClient

And by the way in case of OutOfMemory exception due the buffering of WebClient: Are you getting OutOfMemoryExceptions when uploading large files?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜