ASP.NET C# 文件下载速度限制

寻技术 C#编程 / ASP.NET编程 2023年12月09日 135

参考了别人的代码,然后自己修改了一下

        public static bool ResponseFile(HttpContext context, string _fullPath, long _speed)
        {
            HttpRequest _Request = context.Request;
            HttpResponse _Response = context.Response;
            string strFileName = new FileInfo(_fullPath).Name;
            try
            {
                FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                BinaryReader br = new BinaryReader(myFile);
                try
                {
                    _Response.AddHeader("Accept-Ranges", "bytes");
                    _Response.Buffer = false;
                    long fileLength = myFile.Length;
                    long startBytes = ;
                    
                    _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                    if (startBytes != )
                    {
                        _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - , fileLength));
                    }
                    _Response.AddHeader("Connection", "Keep-Alive");
                    _Response.ContentType = "application/octet-stream";
                    _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8));

                    int pack = ; //10K bytes       进行拆包,每包大小                   
                    byte[] buff = new byte[pack];
                    var contentLength = br.Read(buff, , pack);
                    double d =  / (_speed / pack); // 限速时每个包的时间
                    Stopwatch wa = new Stopwatch();
                    while (contentLength != )
                    {
                        if (_Response.IsClientConnected)
                        {
                            wa.Restart();
                            _Response.BinaryWrite(buff);
                            _Response.Flush();
                            contentLength = br.Read(buff, , pack);
                            wa.Stop();
                            if (wa.ElapsedMilliseconds < d) //如果实际带宽小于限制时间就不需要等待
                            {
                                Thread.Sleep((int)(d - wa.ElapsedMilliseconds));
                            }
                        }
                        else
                        {
                            break;
                        }
                    }                     
                }
                catch
                {
                    return false;
                }
                finally
                {
                    br.Close();
                    myFile.Close();
                }
            }
            catch
            {
                return false;
            }
            return true;
        }

 

关闭

用微信“扫一扫”