1

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.

2
  • Did you ever find out an answer for this? Commented Jul 25, 2013 at 20:47
  • @cjohns no, I did not find an answer. Commented Jul 26, 2013 at 7:03

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

2 Comments

No, I haven't. I just tried replacing my GetAsync with GetByteArrayAsync, but got syntax errors. Simply running the one-line client.GetByteArrayAsync(address); threw "one or more exceptions have occured".
Thanks but that's still giving me "one or more errors have occurred". Also, I'm using ASP.NET 4.0 (not 4.5). I also tried changing my action to return a ByteArrayContent, but it didn't make a difference. Note, when I call the Web API by pasing the URL in my browser, no error is thrown and the file is downloaded and shown in my browser. Just the HttpClient code doesn't seem to be working. (My original method didn't throw any errors.)
1

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);
        }
    }

8 Comments

I don't think the API didn't return the Stream. I just simply need the user to get the file... so we need to do something with the stream. I can't use Response.WriteFile or something like because it gives me "Response is not available in this context."
I'm missing something here...I get how to create the file...I need it to be downloaded...are you saying you can't actually download it to the browser in the same request? Hope my issue is clear.
@Rivka I'm confused, you said you want to use HttpClient. But now you are saying you want to use a browser. I don't understand your scenario.
Are those two mutually exclusive? Let's put it this way: Forget the stream - after I get any result from the server via HttpClient (could be ReadAsAsync()), is it possible to download a file? Just like I would normally do with Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", String.Format("attachment;filename=\"{0}\"", file.Name)); Response.AddHeader("Content-Length", file.Length.ToString()); Response.WriteFile(file.FullName); Response.End(); This is a real simple question: get a response from a server using HttpClient and then download a file.
@Rivka Where is your HTTPClient code running? What user-agent do you want to use to download the file with? I honestly don't understand what you are trying to do.
|
-1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.