简体   繁体   中英

c# mvc - Downloading huge files hangs web application

I have a feature that allows user to download files from server by clicking on the fileName on the web page. I am using ASP.Net MVC5. Downloads of any size (tried upto 2GB) works fine with my current implementation. The problem is when downloading files that are >200MB, web application hangs until the complete download is finish.

Current implementation: When User clicks on fileName in a grid, it triggers the 'Download' ActionMethod that is in 'DocumentController' and thus the file is downloaded from server.

Then 2 approaches came to my mind to fix the above problem:

Approach1 : Using Async feature. I am newbie to async programming. So could you please update my code below to behave asyn if this is the best approach.

 public ActionResult Download(string filePath, string fileName)
    {
        try
        {
            if(!string.IsNullOrEmpty(filePath))
            {
                filePath = Path.Combine(baseUrl, filePath);
                string contentType = MimeMapping.GetMimeMapping(fileName);

                TransmitFile(filePath, fileName);
            }
        }
        catch(Exception ex) { }
        return Content("");
    }

    private void TransmitFile(string fullPath, string outFileName)
    {
        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;

        // Identify the file to download including its path.
        string filepath = fullPath;

        // Identify the file name.
        string filename = System.IO.Path.GetFileName(filepath);

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


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

            Response.Clear();
            Response.ContentType = MimeMapping.GetMimeMapping(filename);
            Response.AddHeader("content-disposition", "attachment; filename=\"" + outFileName + "\"");
            Response.AddHeader("Content-Length", iStream.Length.ToString());

            // 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 output.
                    Response.Flush();

                    buffer = new Byte[10000];
                    dataToRead = dataToRead - length;
                }
                else
                {
                    //prevent infinite loop if user disconnects
                    dataToRead = -1;
                }
            }
        }
        catch (Exception ex)
        {
            throw new ApplicationException(ex.Message);
        }
        finally
        {
            if (iStream != null)
            {
                //Close the file.
                iStream.Close();
            }
            Response.Close();
        }
    }

Approach 2 : Ajax call to 'Download' ActionMethod. This did not work as well for me.

function downloadFile() {    
var data = //Gets data object using some action and works fine

$.ajax({
    url: '/Document/IsFileExistOnServer',
    data: { 'filePath': data.path },
    type: 'GET',
    success: function (isFileExist) {
        if (typeof isFileExist != "undefined" && isFileExist != null) {
            if (isFileExist == "true") {
                window.location = '@Url.Action("Download", "Document", new { filePath =' + data.path + ', fileName =' + data.name + ' })';                    
            }
            else {
                alert("File Not found. Cannot download");
            }
        }
    },
    error: function (data) {
        alert("Error occured. Please try again.")
    }
});

}

The problem with ajax call is, the View that is requesting the File to Download is associated with another Controller (HomeController) and on clicking download, current page is getting redirected to a link like this: http://localhost:59740/Home/Details/@Url.Action(Download,Document,new {filePath=2017/05/TestFile.db,fileName=test1Gb.db})

Please can someone help me with a best way to do this. Thanks in advance !!!

I think you should use this one:

Response.OutputStream.WriteAsync(buffer, 0, length);

instead of this:

Response.OutputStream.Write(buffer, 0, length);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM