这个是一个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(); }
版权声明:除特别声明外,本站所有文章皆是本站原创,转载请以超链接形式注明出处!