在使用 Nancy API 时 需要给web 传递一个图片,这个图片不是物理文件而是临时生成的数据流
尝试Response.AsFile(streamxxx,"image/jpg") Response.FromStream(streamxxx,"image/jpg") 都失败前端无法展示
查询资料 给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);
}
};
}
}
/// <summary>
/// 版 本
/// Copyright (c)
/// 创建人:
/// 日 期:
/// 描 述:扩展图片流传递
/// </summary>
public static class Extensions
{
public static Response FromByteArray(this IResponseFormatter formatter, byte[] body, string contentType = null)
{
return new ByteArrayResponse(body, contentType);
}
}
最终
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return Response.FromByteArray(ms.ToArray(), "image/jpg");