【问题标题】:How to make an image handler in NancyFx如何在 NancyFx 中制作图像处理程序
【发布时间】:2013-01-06 13:35:09
【问题描述】:

我正在努力将 NancyFX 数据库中字节 [] 中的图像输出到 Web 输出流。我没有足够接近的示例代码,甚至无法在这一点上显示。我想知道是否有人解决了这个问题并可以发布一个sn-p?我基本上只是想从存储在我的数据库中的字节数组中返回图像/jpeg,并将其输出到网络而不是物理文件。

【问题讨论】:

    标签: image outputstream nancy


    【解决方案1】:

    只是以@TheCodeJunkie 的回答为基础,您可以像这样非常轻松地构建“字节数组响应”:

    public class ByteArrayResponse : Response
    {
        /// <summary>
        /// Byte array response
        /// </summary>
        /// <param name="body">Byte array to be the body of the response</param>
        /// <param name="contentType">Content type to use</param>
        public ByteArrayResponse(byte[] body, string contentType = null)
        {
            this.ContentType = contentType ?? "application/octet-stream";
    
            this.Contents = stream =>
                {
                    using (var writer = new BinaryWriter(stream))
                    {
                        writer.Write(body);
                    }
                };
        }
    }
    

    如果你想使用 Response.AsX 语法,它是一个简单的扩展方法:

    public static class Extensions
    {
        public static Response FromByteArray(this IResponseFormatter formatter, byte[] body, string contentType = null)
        {
            return new ByteArrayResponse(body, contentType);
        }
    }
    

    然后在您的路线中,您可以使用:

    Response.FromByteArray(myImageByteArray, "image/jpeg");
    

    您还可以添加处理器以使用字节数组进行内容协商,我已将其快速示例添加到 this gist

    【讨论】:

    • 非常感谢您扩展解决方案,这正是我所需要的。
    • 有没有办法让浏览器缓存请求的字节数组响应?这样处理程序就不会再为同一个 url 工作了?
    • 太糟糕了,缓存是内存中的字节。您不能直接流式传输(使用最少的内存)吗?
    【解决方案2】:

    在您的控制器中,返回带有图像字节流的 Response.FromStream。在旧版本的 nancy 中,它曾经被称为 AsStream。

    Get["/Image/{ImageID}"] = parameters =>
    {
         string ContentType = "image/jpg";
         Stream stream = // get a stream from the image.
    
         return Response.FromStream(stream, ContentType);
    };
    

    【讨论】:

    • 你应该如何使用这个 API 关闭源流?太可怕了。
    • 源流稍后自动处理-github.com/NancyFx/Nancy/issues/786
    • 您必须确保将流位置设置为流的开头:stream.Seek(0, SeekOrigin.Begin),因为FromStream 不会为您执行此操作。
    【解决方案3】:

    您可以从 Nancy 返回一个新的 Response 对象。它的 Content 属性是 Action&lt;Stream&gt; 类型,因此您可以创建一个委托,将您的字节数组写入该流

    var r = new Response();
    r.Content = s => {
       //write to s
    };
    

    不要忘记设置ContentType 属性(您可以使用MimeTypes.GetMimeType 并传递名称,包括扩展名)还有一个StreamResponse,它继承自Response 并提供不同的构造函数(对于更好的语法,您可以在您的路线中使用return Response.AsStream(..) .. 只是语法糖果)

    【讨论】:

    • 感谢您的帮助,我喜欢您提供的替代解决方案。
    • 属性名好像改成了Contents
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-08
    相关资源
    最近更新 更多