使用Akka将文件从服务器流传输到客户端 [英] Streaming file from server to client using Akka
问题描述
基本上,我想允许用户从服务器下载csv文件。假设服务器上已经存在CSV文件。 API端点通过GET / export公开。如何将文件从Akka HTTP服务器流式传输到客户端?
Basically I want to allow a user to download a csv file from the server. Assume the CSV file already exists on the server. A API endpoint is exposed via GET /export. How do I stream the file from Akka HTTP server to client? This is what I have so far...
服务:
def export(): Future[IOResult] = {
FileIO.fromPath(Paths.get("file.csv"))
.to(Sink.ignore)
.run()
}
路线:
pathPrefix("export") {
pathEndOrSingleSlash {
get {
complete(HttpEntity(ContentTypes.`text/csv`, export())
}
}
}
推荐答案
Akka-Stream API允许您直接从 Source [ByteString,_]
创建实体,因此您可以按照
The Akka-Stream API allow you to create an entity directly out of a Source[ByteString, _]
, so you can do something along the lines of
pathPrefix("export") {
pathEndOrSingleSlash {
get {
complete(HttpEntity(ContentTypes.`text/csv(UTF-8)`, FileIO.fromPath(Paths.get("file.csv")))
}
}
}
请注意,这样,您的服务器代码将不需要将整个CSV文件提取到mem中在通过电线发送之前。文件内容将在启用反压的流中发送。 此处。
Note that this way your server code will not need to ingest the whole CSV file in memory before sending it over the wire. The file contents will be sent over in a backpressure-enabled stream. More on this here.
这篇关于使用Akka将文件从服务器流传输到客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!