使用 Akka 将文件从服务器流式传输到客户端 [英] Streaming file from server to client using Akka

查看:35
本文介绍了使用 Akka 将文件从服务器流式传输到客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我想允许用户从服务器下载 csv 文件.假设 CSV 文件已存在于服务器上.API 端点通过 GET/export 公开.如何将文件从 Akka HTTP 服务器流式传输到客户端?这是我到目前为止...

服务:

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

路线:

pathPrefix("export") {pathEndOrSingleSlash {得到 {完成(HttpEntity(ContentTypes.`text/csv`,export())}}}

解决方案

Akka-Stream API 允许您直接从 Source[ByteString, _] 中创建实体,因此您可以类似的东西

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

请注意,通过这种方式,您的服务器代码在通过网络发送之前不需要在内存中摄取整个 CSV 文件.文件内容将在启用背压的流中发送.在此处了解更多相关信息.>

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...

Service:

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

Route:

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

解决方案

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")))
    }
  }
}

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆