set*_*ian 20 image outputstream nancy
我正在努力从NancyFX中的数据库中将byte []中的Image输出到Web输出流.我没有示例代码足够接近甚至在此时显示.我想知道是否有人解决了这个问题并且可以发布一个代码片段?我基本上只想从存储在我的数据库中的字节数组中返回image/jpeg,然后将其放到Web而不是物理文件中.
Ste*_*ins 30
只是为了构建@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);
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
然后,如果你想使用Response.AsX语法,它是一个简单的扩展方法:
public static class Extensions
{
public static Response FromByteArray(this IResponseFormatter formatter, byte[] body, string contentType = null)
{
return new ByteArrayResponse(body, contentType);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在您的路线中,您可以使用:
Response.FromByteArray(myImageByteArray, "image/jpeg");
Run Code Online (Sandbox Code Playgroud)
您还可以添加一个处理器来使用带有内容协商的字节数组,我已经为此要点添加了一个快速示例
kri*_*anp 12
在您的控制器中,返回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);
};
Run Code Online (Sandbox Code Playgroud)
从Nancy你可以返回一个新Response对象.它的Content属性是类型,Action<Stream>因此您可以创建一个将您的字节数组写入该流的委托
var r = new Response();
r.Content = s => {
//write to s
};
Run Code Online (Sandbox Code Playgroud)
不要忘记设置ContentType属性(您可以使用MimeTypes.GetMimeType并传递它的名称,包括扩展名)还有一个StreamResponse,它继承Response并提供不同的构造函数(对于您可以return Response.AsStream(..)在路由中使用的更好的语法...只是语法糖果)
| 归档时间: |
|
| 查看次数: |
6497 次 |
| 最近记录: |