I need to pass a file that's obtained via a web service on to the end user. Right now, I'm doing this in two steps:
Obtain file from a secure web service:
Dim client As New Net.WebClient client.Headers.Add("Authorization", String.Format("Bearer {0}", access_token))
Dim data As Byte() = client.DownloadData(uri)
Serve the file to the user via the http response.
This is taking a long time for the end user, as the user has to wait for the server to download the file from the service, and then for the client to download the file from the server.
Is it possible to instead stream the file directly from the web service to the user? If so, what's the best way to do it?
I think the best way to achieve this would be to progressively download the file and buffer it into the response so it progressively downloads to the client. This way, the end user doesn't have to wait for the server to completely download the file and send it back. It will just stream the file content as it downloads it from the other location. As a bonus, you don't have to keep the entire file in memory or on disk!
Here's a code sample achieving this:
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With