如何使用C#在MVC中快速下载文件? [英] How can I fast download file in MVC using C#

查看:345
本文介绍了如何使用C#在MVC中快速下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了一个asp.net MVC网站,用户可以下载大型MP3文件(最大120 MB)并且工作正常。但问题是当我们发送文件的下载请求然后下载正常启动但我们不能在网站上执行任何操作,直到文件完全下载(没有得到任何其他请求的任何响应)。如何快速下载文件和另一个请求也一起发送响应下载文件?我的文件存储在Microsoft Azure存储blob上。



我尝试过:



I've implemented an asp.net MVC site where users can download large MP3 files (up to 120 MB) and works fine. But the problem is when we send the download request of the file then downloading starts properly but we can not perform any action on site until the file fully download (not getting any response of any another request). How can I do fast download the file and another request also send the response together downloading files? My files are stored on Microsoft Azure storage blob.

What I have tried:

public async Task<string> DownloadMediaFile(string url)
        {
            int lstidx = url.LastIndexOf('/');
            int charslngth = url.Length - 1;
            string getFileNameWithExtension = url.Substring(lstidx + 1, charslngth - lstidx);           
            string fileName = getFileNameWithExtension;
            //Create a stream for the file
            Stream stream = null;

            //This controls how many bytes to read at a time and send to the client
            int bytesToRead = 10000;

            // Buffer to read bytes in chunk size specified above
            byte[] buffer = new Byte[bytesToRead];

            // The number of bytes read
            try
            {
                //Create a WebRequest to get the file
                HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(url);

                //Create a response for this request
                HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();

                if (fileReq.ContentLength > 0)
                    fileResp.ContentLength = fileReq.ContentLength;

                //Get the Stream returned from the response
                stream = fileResp.GetResponseStream();

                // prepare the response to the client. resp is the client Response
                var resp = Response;

                //Indicate the type of data being sent
                resp.ContentType = "application/octet-stream";

                //Name the file 
                resp.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
                resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());

                int length;
                do
                {
                    // Verify that the client is connected.
                    if (resp.IsClientConnected)
                    {
                        // Read data into the buffer.
                        length = stream.Read(buffer, 0, bytesToRead);

                        // and write it out to the response's output stream
                        resp.OutputStream.Write(buffer, 0, length);

                        // Flush the data
                        resp.Flush();

                        //Clear the buffer
                        buffer = new Byte[bytesToRead];
                    }
                    else
                    {
                        // cancel the download if client has disconnected
                        length = -1;
                    }
                } while (length > 0); //Repeat until no data is read
            }
            finally
            {                
                if (stream != null)
                {
                    //Close the input stream
                    stream.Close();
                }
            }
            return "success";
        }

推荐答案

这很可能是由于会话状态行为 - 默认情况下,它设置为必需,这意味着一次只能提供一个请求。



因为你似乎没有使用会话状态或者 TempData 在您的操作中,您可以将其禁用。不幸的是,您需要在控制器级别执行此操作,因此您需要将 DownloadMediaFile 操作移动到其他控制器。然后将 SessionState 属性添加到该控制器:

This is most likely due to the session state behaviour - by default, it's set to Required, which means only one request can be served at a time.

Since you don't seem to be using session state or TempData in your action, you can disable it. Unfortunately, you need to do that at the controller level, so you'll need to move your DownloadMediaFile action to a different controller. Then add the SessionState attribute to that controller:
[SessionState(SessionStateBehavior.Disabled)]
public class DownloadController : Controller
{
    ...


在单独的帖子中下载


这篇关于如何使用C#在MVC中快速下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆