ASP.NET C# 文件上传速度限制

寻技术 C#编程 / ASP.NET编程 2023年07月11日 92

这个是一个Restful上传文件的实现方法,我们可以在上传过程中通过线程等待来现实限速功能

        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="fileStream"></param>
        public void FileUpload(string fileName, Stream fileStream)
        {

            FileStream fileToupload = new FileStream("D:\\FileUpload\\" + fileName, FileMode.Create);

            int _speed =  * ; // 1M/S
            int pack = ; //10K bytes  
            byte[] bytearray = new byte[pack];
            double limit =  / (_speed / pack); // 限速时每个包的时间

            int bytesRead, totalBytesRead = ;
            do
            {
                Stopwatch wa = new Stopwatch();
                wa.Restart();
                bytesRead = fileStream.Read(bytearray, , bytearray.Length);
                totalBytesRead += bytesRead;
                wa.Stop();
                if (wa.ElapsedMilliseconds < limit) //如果实际带宽小于限制时间就不需要等待
                {
                    Thread.Sleep((int)(limit - wa.ElapsedMilliseconds));
                }
               
            } while (bytesRead > );

            fileToupload.Write(bytearray, , bytearray.Length);
            fileToupload.Close();
            fileToupload.Dispose();
        } 

 

关闭

用微信“扫一扫”