Reputation: 13733
I have a web api controller and I want to write a function that simulates a file download (not a real file - just something that is generated on the fly).
What I would like to do is send that api a parameter with file size and have it return a "binary" file generated on the fly.
something similar to this php code:
<?php
$filesize = 20971520; // 20 Mo
if (isset($_POST['d'])) {
header('Cache-Control: no-cache');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '. $filesize);
for($i = 0 ; $i < $filesize ; $i++) {
echo chr(255);
}
}
?>
The closest solution I found was something like this:
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new StreamContent(new FileStream(@"path to image")); // this file stream will be closed by lower layers of web api for you once the response is completed.
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
I tried playing around with it and change it but had no luck.
would appriciate if someone could point me in the right direction and help me out.
Thanks
Upvotes: 0
Views: 738
Reputation: 7505
Something like this?
public class FakeDownloadController: ApiController
{
public HttpResponseMessage Get([FromUri] int size)
{
var result = new HttpResponseMessage(HttpStatusCode.OK);
byte[] data = new byte[size];
var stream = new MemoryStream(data);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/binary");
var contentDisposition = new ContentDispositionHeaderValue("attachment");
contentDisposition.FileName = string.Format("{0}.{1}", "dummy","bin");
result.Content.Headers.ContentDisposition = contentDisposition;
return result;
}
}
usage:
http://localhost:port/api/FakeDownload/?size=6543354
will return a ~6 MB file filled with NULL, called "dummy.bin".
Hope that helps.
Upvotes: 1