Download a large file - connect to a Reset server

I have an asp.net site that allows the user to upload quite large files - from 30 to 60 mb. Sometimes the download works fine, but often it fails at some other time before the download ends with a message that the connection to the server was reset.

Initially, I just used Server.TransmitFile, but after a little reading, I now use the code below. I also set the value of Server.ScriptTimeout to 3600 in the Page_Init event.

private void DownloadFile(string fname, bool forceDownload)
        {
            string path = MapPath(fname);
            string name = Path.GetFileName(path);
            string ext = Path.GetExtension(path);
            string type = "";

            // set known types based on file extension  

            if (ext != null)
            {
                switch (ext.ToLower())
                {
                    case ".mp3":
                        type = "audio/mpeg";
                        break;

                    case ".htm":
                    case ".html":
                        type = "text/HTML";
                        break;

                    case ".txt":
                        type = "text/plain";
                        break;

                    case ".doc":
                    case ".rtf":
                        type = "Application/msword";
                        break;
                }
            }

            if (forceDownload)
            {
                Response.AppendHeader("content-disposition",
                    "attachment; filename=" + name.Replace(" ", "_"));
            }

            if (type != "")
            {
                Response.ContentType = type;
            }
            else
            {
                Response.ContentType = "application/x-msdownload";
            }

            System.IO.Stream iStream = null;

            // Buffer to read 10K bytes in chunk:
            byte[] buffer = new Byte[10000];

            // Length of the file:
            int length;

            // Total bytes to read:
            long dataToRead;

            try
            {
                // Open the file.
                iStream = new System.IO.FileStream(path, System.IO.FileMode.Open,
                            System.IO.FileAccess.Read, System.IO.FileShare.Read);


                // Total bytes to read:
                dataToRead = iStream.Length;

                //Response.ContentType = "application/octet-stream";
                //Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);

                // Read the bytes.
                while (dataToRead > 0)
                {
                    // Verify that the client is connected.
                    if (Response.IsClientConnected)
                    {
                        // Read the data in buffer.
                        length = iStream.Read(buffer, 0, 10000);

                        // Write the data to the current output stream.
                        Response.OutputStream.Write(buffer, 0, length);

                        // Flush the data to the HTML output.
                        Response.Flush();

                        buffer = new Byte[10000];
                        dataToRead = dataToRead - length;
                    }
                    else
                    {
                        //prevent infinite loop if user disconnects
                        dataToRead = -1;
                    }
                }
            }
            catch (Exception ex)
            {
                // Trap the error, if any.
                Response.Write("Error : " + ex.Message);
            }
            finally
            {
                if (iStream != null)
                {
                    //Close the file.
                    iStream.Close();
                }
                Response.Close();
            }

        }
+3
source share
4 answers

, web.config. sessionState = "InProc" sessionState = "StateServer".

0

<configuration>
  <system.web>
    <httpRuntime executionTimeout="3600"/>
  </system.web>
</configuration>

-?

, , , :

int length;
while(  Response.IsClientConnected && 
       (length=iStream.Read(buffer,0,buffer.Length))>0 ) 
{
  Response.OutputStream.Write(buffer,0,length);
  Response.Flush();
}

, , .

-, .

+2

, FileUpload Control, a > 4 . reset. , :

web.config , , . 4096 (), 4 (). maxRequestLength httpRuntime. , maxRequestLength Web.config.

, 10 (10240 ). (REPLACE '[' '<' ']' ' > ')

 []
[System.web]
[httpRuntime maxRequestLength = "10240" /]
[/system.web]
[/]

+2

As a result, I worked with Response.End and also executed the using statement with the file stream. Here is the code I have:

public partial class ssl_Report_StreamReport : BaseReportPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Get the parameters
        string reportName = Utils.ParseStringRequest(Request, "reportName") ?? string.Empty;
        string reportGuid = Session["reportGuid"].ToString();
        string path = Path.Combine(ReportPath(), Utils.GetSessionReportName(reportName, reportGuid));

        using (var fileStream = File.Open(path, FileMode.Open))
        {
            Response.ClearHeaders();
            Response.Clear();
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment; filename=\"" + reportName + "\"");
            Response.AddHeader("Content-Length", fileStream.Length.ToString(CultureInfo.InvariantCulture));
            StreamHelper.CopyStream(fileStream, Response.OutputStream);
            Response.Flush();
            Response.End();
        }

        ReportProcessor.ClearReport(Session.SessionID, path);
    }
}


public static class StreamHelper
{
    public static void CopyStream(Stream input, Stream output)
    {
        byte[] buffer = new byte[32768];
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            output.Write(buffer, 0, read);
        }
    }
}
0
source

Source: https://habr.com/ru/post/1698086/


All Articles