简体   繁体   中英

Accept and download stream content from ASP.NET Web API using HTTPClient

I have an ASP.NET Web API action which creates a file and returns a stream content:

public HttpResponseMessage Get(string filePath)
{
    // create file
    var file = FileConverter.GenerateExcelFile(filePath);

    var stream = new FileStream(filePath, FileMode.Open);

    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
    result.Content.Headers.ContentDisposition.FileName = Path.GetFileName(filePath);
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    return result;
}

I would like to use HttpClient to download the returned file. Here's what I have now:

    client.GetAsync(address).ContinueWith(
        (requestTask) =>
        {
             HttpResponseMessage response = requestTask.Result;

            // response.EnsureSuccessStatusCode();

            response.Content.ReadAsStreamAsync().ContinueWith(
                        (readTask) =>
                        { 
                            var stream = readTask.Result; 
                        });
        });

How do I force the actual download after getting the result?

Edit: I'm using ASP.NET 4.0 WebForms.

Have you thought about just calling :

client.GetByteArrayAsync(address)

instead to get the byte array result and then just save it to a memory stream?

Edit::

Try something like this:

var contentBytes = await client.GetByteArrayAsync(address);
Stream stream = new MemoryStream(contentBytes);

Why do you think the download has not happened?

By default when you do GetAsync HTTP client with create MemoryStream as a buffer with the result. ReadAsStreamAsync is just returning that buffered StreamContent.

Edit: You can create a file like this,

  using (FileStream fs = new FileStream("file.txt", FileMode.Create)) {
           stream.CopyTo(fs);
        }
    }

HttpClient runs on server side not in web browser so it's really confusing what you are trying to achieve here. If you really need to use HttpClient yoou can save the result stream to a file stream as you can read in comments.

If you want the file to be downloaded in a web browser you don't need and can't use HttpClient. As you've written in a comment it already works, just create a link what the user can click on. Or search for ajax download file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM