使用Akka从服务器到客户端的流文件

问题描述:

基本上我想允许用户从服务器下载csv文件。假定服务器上已经存在CSV文件。 API端点通过GET/export显示。如何将文件从Akka HTTP服务器流式传输到客户端?这是我迄今为止...使用Akka从服务器到客户端的流文件

服务:

def export(): Future[IOResult] = { 
    FileIO.fromPath(Paths.get("file.csv")) 
     .to(Sink.ignore) 
     .run() 
} 

路线:

pathPrefix("export") { 
    pathEndOrSingleSlash { 
    get { 
     complete(HttpEntity(ContentTypes.`text/csv`, export()) 
    } 
    } 
} 

的阿卡,流API允许你直接创建一个实体了Source[ByteString, _]的,所以你可以按照以下方式做点什么

pathPrefix("export") { 
    pathEndOrSingleSlash { 
    get { 
     complete(HttpEntity(ContentTypes.`text/csv(UTF-8)`, FileIO.fromPath(Paths.get("file.csv"))) 
    } 
    } 
} 

请注意,这样你的服务器代码就不需要了在通过电线发送之前将其存储在内存中的整个CSV文件。文件内容将在支持反压的流中发送。更多关于这个here

+0

谢谢!对于我来说,下一步就是将文件流式传输到客户端,因为不必在服务器上首先创建临时文件就可以写入行。 – perry

+0

@perry你可以请你分享你的做法,接下来做什么? – oblivion

+1

'def export():Source [ByteString,_] = Source.fromPublisher(db.stream(things.result.transactionally.withStatementParameters(fetchSize = 1000)))' where'things'是一个TableQuery – perry