使用WEB API模拟文件下载

时间:2014-02-10 06:27:05

标签: c# asp.net-web-api

我有一个web api控制器,我想编写一个模拟文件下载的函数(不是真正的文件 - 只是即时生成的东西)。

我想做的是发送api一个带文件大小的参数,让它返回一个动态生成的“二进制”文件。

类似于这个PHP代码:

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

我找到的最接近的解决方案是这样的:

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

我试着玩它并改变它但没有运气。

如果有人能指出我正确的方向并帮助我,

会很高兴。

由于

1 个答案:

答案 0 :(得分:1)

这样的东西?

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

用法:

http://localhost:port/api/FakeDownload/?size=6543354

将返回一个填充NULL的~6 MB文件,名为“dummy.bin”。

希望有所帮助。

相关问题