Reputation: 2202
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.
Upvotes: 1
Views: 9711
Reputation: 4749
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.
Upvotes: -1
Reputation: 142044
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);
}
}
Upvotes: 1
Reputation: 10604
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);
Upvotes: 3