我認爲最好的方法是逐步下載文件並將其緩存到響應中,以逐步下載到客戶端。這樣,最終用戶不必等待服務器完全下載文件並將其發回。它只會在從其他位置下載文件內容時傳輸文件內容。作爲獎勵,您不必將整個文件保存在內存中或磁盤上!
下面是一個代碼示例實現這一目標:
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();
}
但是你把它,你仍然需要通過自己,你是最終的文件和最終用戶之間的代理流。您是否能夠在第一次流式傳輸時將文件存儲在您自己的服務器上,然後隨後的請求可以下載您保存的版本? – Darren
我可以存儲該文件,但每個文件只能由單個用戶下載一次,因此該選項中的實用程序很少。我只是希望加快這個過程。 – Andy