And*_*ndy 3 .net c# vb.net asp.net
我需要将通过Web服务获得的文件传递给最终用户.现在,我分两步完成:
从安全的Web服务获取文件:
Dim client As New Net.WebClient client.Headers.Add("Authorization",String.Format("Bearer {0}",access_token))
昏暗数据As Byte()= client.DownloadData(uri)
通过http响应将文件提供给用户.
这对最终用户来说需要很长时间,因为用户必须等待服务器从服务下载文件,然后客户端从服务器下载文件.
是否可以将文件直接从Web服务流式传输给用户?如果是这样,最好的方法是什么?
我认为实现这一目标的最佳方法是逐步下载文件并将其缓冲到响应中,以便逐步下载到客户端.这样,最终用户不必等待服务器完全下载文件并将其发回.它将在从其他位置下载文件内容时直接传输文件内容.作为奖励,您不必将整个文件保留在内存或磁盘上!
这是一个实现此目的的代码示例:
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();
}
Run Code Online (Sandbox Code Playgroud)