【发布时间】:2013-01-06 13:35:09
【问题描述】:
我正在努力将 NancyFX 数据库中字节 [] 中的图像输出到 Web 输出流。我没有足够接近的示例代码,甚至无法在这一点上显示。我想知道是否有人解决了这个问题并可以发布一个sn-p?我基本上只是想从存储在我的数据库中的字节数组中返回图像/jpeg,并将其输出到网络而不是物理文件。
【问题讨论】:
标签: image outputstream nancy
我正在努力将 NancyFX 数据库中字节 [] 中的图像输出到 Web 输出流。我没有足够接近的示例代码,甚至无法在这一点上显示。我想知道是否有人解决了这个问题并可以发布一个sn-p?我基本上只是想从存储在我的数据库中的字节数组中返回图像/jpeg,并将其输出到网络而不是物理文件。
【问题讨论】:
标签: image outputstream nancy
只是以@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
【讨论】:
在您的控制器中,返回带有图像字节流的 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);
};
【讨论】:
stream.Seek(0, SeekOrigin.Begin),因为FromStream 不会为您执行此操作。
您可以从 Nancy 返回一个新的 Response 对象。它的 Content 属性是 Action<Stream> 类型,因此您可以创建一个委托,将您的字节数组写入该流
var r = new Response();
r.Content = s => {
//write to s
};
不要忘记设置ContentType 属性(您可以使用MimeTypes.GetMimeType 并传递名称,包括扩展名)还有一个StreamResponse,它继承自Response 并提供不同的构造函数(对于更好的语法,您可以在您的路线中使用return Response.AsStream(..) .. 只是语法糖果)
【讨论】:
Contents。