我正在努力从我的NancyFX数据库中的byte[]输出图像到web输出流中。在这一点上,我没有足够接近的示例代码来显示。我想知道是否有人已经解决了这个问题,并可以发布一个代码片段?我基本上只想从存储在数据库中的字节数组返回image/jpeg,并将其输出到web上,而不是物理文件。
发布于 2013-01-23 16:14:10
根据@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中添加了一个快速示例
发布于 2015-02-20 15:43:57
在您的控制器中,返回带有图像字节流的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);
};
发布于 2013-01-23 14:52:55
您可以从Nancy返回一个新的Response
对象。它的Content
属性是Action<Stream>
类型,因此您只需创建一个将字节数组写入该流的委托
var r = new Response();
r.Content = s => {
//write to s
};
不要忘记设置ContentType
属性(您可以使用MimeTypes.GetMimeType
并向其传递名称,包括扩展名)。还有一个StreamResponse
,它继承自Response
并提供不同的构造函数(对于更好的语法,您可以在路由中使用return Response.AsStream(..)
。)只是语法糖果)
https://stackoverflow.com/questions/14473510
复制相似问题