如何在asp.net mvc 3中限制速度下载文件

时间:2012-10-30 10:02:39

标签: c# asp.net-mvc web-applications download

我已阅读有关codeproject的这篇文章,但我不知道如何将其应用于asp.net mvc 3 http://www.codeproject.com/Articles/18243/Bandwidth-throttling

以下是在我的项目中下载文件的代码

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在这个问题上支持我,非常感谢!

1 个答案:

答案 0 :(得分: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();
}

并根据您的需要调整bps。