我有一个用户可以下载文件的站点.有些文件非常大(最大的是323 MB).当我测试它以尝试下载此文件时,我得到内存不足异常.我知道下载文件的唯一方法如下.我使用下面的代码的原因是因为URL是编码的,我不能让用户直接链接到该文件.有没有其他方法可以下载此文件而无需将整个内容读入字节数组?
FileStream fs = new FileStream(context.Server.MapPath(url), FileMode.Open,
FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
long numBytes = new FileInfo(context.Server.MapPath(url)).Length;
byte[] bytes = br.ReadBytes((int) numBytes);
string filename = Path.GetFileName(url);
context.Response.Buffer = true;
context.Response.Charset = "";
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.ContentType = "application/x-rar-compressed";
context.Response.AddHeader("content-disposition", "attachment;filename=" + filename);
context.Response.BinaryWrite(bytes);
context.Response.Flush();
context.Response.End();
Run Code Online (Sandbox Code Playgroud)
Pet*_*sen 16
代替
context.Response.BinaryWrite(bytes);
Run Code Online (Sandbox Code Playgroud)
使用
context.Response.TransmitFile(context.Server.MapPath(url));
Run Code Online (Sandbox Code Playgroud)
这样可以避免将整个文件读入内存.