使用 ASP.Net Webapi 流式传输大图像 [英] Streaming large images using ASP.Net Webapi

查看:44
本文介绍了使用 ASP.Net Webapi 流式传输大图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在尝试使用 ASP.Net WebApi 返回大图像文件,并使用以下代码将字节流式传输到客户端.

We are trying to return large image files using ASP.Net WebApi and using the following code to stream the bytes to the client.

public class RetrieveAssetController : ApiController
{
    // GET api/retrieveasset/5
    public HttpResponseMessage GetAsset(int id)
    {
        HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
        string filePath = "SomeImageFile.jpg";

        MemoryStream memoryStream = new MemoryStream();

        FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read);

        byte[] bytes = new byte[file.Length];
        file.Read(bytes, 0, (int)file.Length);

        memoryStream.Write(bytes, 0, (int)file.Length);

        file.Close();

        httpResponseMessage.Content =  new ByteArrayContent(memoryStream.ToArray());
        httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        httpResponseMessage.StatusCode = HttpStatusCode.OK;

        return httpResponseMessage;
    }
}

上面的代码工作正常,但我们处理的一些文件的大小可能为 2 GB 及以上,从而导致连接超时.过去我们使用过类似于下面的代码(使用 HttpHandlers)将响应分块到响应流,以保持连接成功.

The above code works fine but some of the files that we deal with could be 2 GB and upwards in size resulting in connection timeouts. We have used code similar to below in the past (using HttpHandlers) to chunk the response to the response stream to keep the connection alive with success.

byte[] b = new byte[this.BufferChunkSize];
int byteCountRead = 0;

while ((byteCountRead = stream.Read(b, 0, b.Length)) > 0)
{
    if (!response.IsClientConnected) break;

    response.OutputStream.Write(b, 0, byteCountRead);
    response.Flush();
}

我们如何使用前面显示的新 WebAPI 编程模型使用类似的技术?

How can we use a similar technique using the new WebAPI programming model shown earlier?

推荐答案

是的,您可以使用 PushStreamContent.如果您将其与异步执行(使用异步 lambdas)结合起来,您可能会得到更有效的结果.

Yes you can use PushStreamContent. And if you combine it with asynchronous execution (usin i.e. async lambdas), you might get even more effective results.

本月早些时候我在博客中介绍了这种方法 - http://www.strathweb.com/2013/01/asynchronously-streaming-video-with-asp-net-web-api/.

I have blogged about this approach earlier this month - http://www.strathweb.com/2013/01/asynchronously-streaming-video-with-asp-net-web-api/.

这个例子使用了一个视频文件,原理是一样的——将字节的数据下推给客户端.

The example used a video file, the principle is the same - pushing down bytes of data to the client.

这篇关于使用 ASP.Net Webapi 流式传输大图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆