我认为实现这一点的最佳方法是逐步下载文件并将其缓冲到响应中,以便逐步下载到客户端。这样,最终用户不必等待服务器完全下载文件并将其发回。它只会在从其他位置下载文件内容时流式传输文件内容。作为奖励,您不必将整个文件保存在内存或磁盘上!
这是实现此目的的代码示例:
protected void downloadButton_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "MyFile.exe"));
Response.Buffer = true;
Response.ContentType = "application/octet-stream";
using (var downloadStream = new WebClient().OpenRead("http://otherlocation.com/MyFile.exe")))
{
var uploadStream = Response.OutputStream;
var buffer = new byte[131072];
int chunk;
while ((chunk = downloadStream.Read(buffer, 0, buffer.Length)) > 0)
{
uploadStream.Write(buffer, 0, chunk);
Response.Flush();
}
}
Response.Flush();
Response.End();
}