Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing file from web service to client in ASP.NET

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:

  1. 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)

  2. 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?

like image 314
Andy Avatar asked Sep 12 '25 05:09

Andy


1 Answers

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();
    }
like image 153
Bredstik Avatar answered Sep 14 '25 19:09

Bredstik