I use the code below to put a filestream into a response message, returned by an MVC controller. But how do I get the stream on the client side? Any any comment highly appreciated! Thanks!
Server:
string filename = @"c:\test.zip";
FileStream fs = new FileStream(filename, FileMode.Open);
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new StreamContent(fs);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return response;
If you're simply trying to download the binary data, you should be using the FileContentResult type or the FileStreamResult type, accessible as the File method on the Controller class.
Here's a simple example:
string filename = @"c:\test.zip";
var bytes = System.IO.File.ReadAllBytes(filename);
return File(bytes, "application/octet-stream", "whatevernameyouneed.zip");
You'd probably want to add code to make sure the file exists,etc. If you're curious, you can read about the ReadAllBytes method on MSDN as well.
In your WebForms project, you can read the response from this controller rather easily:
var client = new HttpClient();
var response = await client.GetAsync("protocol://uri-for-your-MVC-project");
if(response.IsSuccessStatusCode)
{
// Do *one* of the following:
string content = await response.Content.ReadAsStringAsync();
// do something with the string
// ... or ...
var bytes = await response.Content.ReadAsByteArrayAsync();
// do something with byte array
// ... or ...
var stream = await response.Content.ReadAsStreamAsync();
// do something with the stream
}
The manner in which you read the response if up to you; as you haven't really described what the client site is supposed to do with the file you're reading, it's hard to be more specific.
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