使用Nancy流(SqlFile-)Stream [英] Stream an (SqlFile-)Stream using Nancy
问题描述
我想知道如何通过我们的Nancy-API直接将SqlFileStream发送给客户端(而不是在内存中加载流).
I was wondering how to send an (in my case) SqlFileStream directly to the client through our Nancy-API without loading the stream in memory.
到目前为止,我成功地传递了流,但是Nancy的StreamResponse将源流(= SqlFileStream)复制到了输出流,这导致了巨大的内存增加.我希望它可以将流发送通过的地方.
So far I succeeded in passing the stream, but Nancy's StreamResponse copies the sourcestream (=SqlFileStream) to the outputstream which causes a massive memory increase. Where I would just like it to send the stream through.
我在WebApi中进行了这项工作,其中WebApi在Owin管道中进行了注册. 没有明显的内存增加,当我们谈论很大的流(> 100MB)时,这是很棒的. 但是,当然,如果可能的话,我宁愿坚持一个API-application-framework.
I made this work in WebApi where WebApi was registered in the Owin-pipeline. No memory increase is noticeable, which is great when we are talking about pretty big streams (>100MB). But of course I'd rather stick to one API-application-framework if possible.
有什么提示吗?
推荐答案
我想我找到了解决方案.最后做起来并不难.
I think I found a solution. It wasn't too difficult to do in the end.
我创建了一个自定义的Nancy.Response => FlushingStreamResponse. 如果这是我们的GET的结果,则将其传递给流和mimetype会导致立即向客户端流式传输.
I created a custom Nancy.Response => FlushingStreamResponse. Passing it a stream and a mimetype, results in immediate streaming to the client when this is the result of our GET.
public class FlushingStreamResponse : Response
{
public FlushingStreamResponse(Stream sourceStream, string mimeType)
{
Contents = (stream) =>
{
var buffer = new byte[16 * 1024];
int read;
while ((read = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, read);
stream.Flush();
}
sourceStream.Dispose();
};
StatusCode = HttpStatusCode.OK;
ContentType = mimeType;
}
}
这篇关于使用Nancy流(SqlFile-)Stream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!