使用WebClient传输非常大的文件

本文关键字:文件 非常 WebClient 传输 使用 | 更新日期: 2023-09-27 18:05:25

我的要求是传输大小为400MB或更大的zip文件;下面的代码至少可以运行40MB;但更多的我将不得不改变byte[] bytes = new byte[50000000];byte[] bytes = new byte[400000000];和maxRequestLength到maxRequestLength="409600";

问题是byte[] bytes = new byte[100000000];返回关于空间不足的错误。那么我如何使用WebClient传输大文件呢??

WebClient client = new WebClient();
client.AllowWriteStreamBuffering = true;
UriBuilder ub = new UriBuilder("http://localhost:57596/UploadImages.ashx");
ub.Query = "ImageName=" + "DataSet" + DataSetId + ".zip";
client.OpenWriteCompleted += (InputStream, eArguments) =>
{
    try
    {
        using (Stream output = eArguments.Result)
        {
            output.Write(ImagesAux, 0, (int)ImagesAux.Length);
            //numeroimagem++;
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
        //throw;
    }
};
client.OpenWriteAsync(ub.Uri);
在UploadImages.ashx

public void ProcessRequest(HttpContext context)
{
    //context.Response.ContentType = "text/plain";
    //context.Response.Write("Hello World");
    string ImageName = context.Request.QueryString["ImageName"];
    string UploadPath = context.Server.MapPath("~/ServerImages/");
    using (FileStream stream = File.Create(UploadPath + ImageName))
    {
        byte[] bytes = new byte[50000000]; // 
        int bytesToRead = 0;
        while ((bytesToRead =
        context.Request.InputStream.Read(bytes, 0, bytes.Length)) != 0)
        {
            stream.Write(bytes, 0, bytesToRead);
            stream.Close();
        }
    }
}
在web . config中

<httpRuntime targetFramework="4.5" maxRequestLength="40960"/>

使用WebClient传输非常大的文件

您永远不应该将所有内容加载到内存中,然后将它们全部写回磁盘,而应该在读取它们时加载部分并将它们写入磁盘。当读取完成后,关闭要写入的流。否则,一旦你达到GB大小,你可以得到一个OutOfMemory非常快。

那么我将把写入字节改为磁盘:

using (FileStream stream = File.Create(UploadPath + ImageName))
{
    byte[] bytes = new byte[50000000]; // 
    int bytesToRead = 0;
    while ((bytesToRead = context.Request.InputStream.Read(bytes, 0, bytes.Length)) != 0)
    {
        stream.Write(bytes, 0, bytesToRead);
        stream.Close();
    }
}

to this:

using (FileStream stream = File.Create(UploadPath + ImageName))
{
    byte[] bytes = new byte[1024];
    long totalBytes = context.Request.InputStream.Length;
    long bytesRead = 0;
    int bytesToRead = bytes.Length;
    if (totalBytes - bytesRead < bytes.Length)
        bytesToRead = (int)(totalBytes - bytesRead);
    bytes = new byte[bytesToRead];
    while ((bytesToRead = context.Request.InputStream.Read(bytes, bytesRead, bytes.Length)) != 0)
    {
        stream.Write(bytes, bytesRead, bytes.Length);
        bytesRead += bytes.Length;
        if (totalBytes - bytesRead < bytes.Length)
            bytesToRead = (int)(totalBytes - bytesRead);
        bytes = new byte[bytesToRead];
    }
    stream.Close();
}

1024将是缓冲区大小