2012-10-30 85 views
1

我讀這篇文章在CodeProject上,但我不知道如何將其應用到asp.net MVC 3 http://www.codeproject.com/Articles/18243/Bandwidth-throttling如何限制速度下載文件在asp.net MVC 3

下面是下載文件的代碼在我的項目中

public ActionResult GetFile(int id) 
{ 
    var f = FileAcc.GetInfo(id); 
    var templateStr = new FileStream(Server.MapPath(f.file_url), FileMode.Open); 
    return File(templateStr, f.file_name); 
} 

Plz在這個問題上支持我,非常感謝!

回答

3

只需提供ThrottledStream.cs在您的項目,並與下面的代碼替換您的GetFile方法 -

public ActionResult GetFile(int id) { 
    var f = FileAcc.GetInfo(id); 
     int bufferSize = 1024, bps = 1024; 
     using (FileStream sourceStream = new FileStream(Server.MapPath(f.file_url), FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize)) { 
      using (Born2Code.Net.ThrottledStream destinationStream = new Born2Code.Net.ThrottledStream(Response.OutputStream, bps)) { 
       byte[] buffer = new byte[bufferSize]; 
       int readCount = sourceStream.Read(buffer, 0, bufferSize); 
       Response.Buffer = false; 
       while (readCount > 0) { 
        destinationStream.Write(buffer, 0, readCount); 
        readCount = sourceStream.Read(buffer, 0, bufferSize); 
       } 
      } 
     } 
    return new EmptyResult(); 
} 

,並調整每次你需要個基點。