scala - 如何使用akka http发送文件作为响应?

标签 scala akka akka-stream akka-http

我对akka世界有点陌生,所以我的知识领域有点小。我正在创建一个 https 服务器并使用 akka 流和 http 处理它,对于特定的 url,我需要将文件发送回客户端。如何使用 akka 流并避免使用 akka 路由来实现这一点。

def handleCall(request:HttpRequest):HttpResponse = {
  logger.info("Request is {}",request)
  val uri:String = request.getUri().path()
  if(uri == "/download"){
    val f = new File("/1000.txt")
    logger.info("file download")
    return HttpEntity(
    //What should i put here if i want to return a text file.
    )
}

最佳答案

如果文件可能很大,那么您不希望在将其发送到客户端之前将整个内容消耗到内存中。这是通过纯基于流的解决方案解决的:

import scala.io
import akka.stream.scaladsl.Source
import akka.http.scaladsl.model.HttpEntity.{Chunked, ChunkStreamPart}
import akka.http.scaladsl.model.{HttpResponse, ContentTypes}

val fileContentsSource : (String, String) => Source[ChunkStreamPart, _] =
  (fileName, enc) =>
    Source
      .fromIterator( io.Source.fromFile(fileName, enc).getLines )
      .map(ChunkStreamPart.apply)


val fileEntityResponse : (String, String) => HttpResponse =
  (fileName, enc) => 
    HttpResponse(entity = Chunked(ContentTypes.`text/plain(UTF-8)`,
                                  fileContentsSource(fileName, enc)))

现在您可以创建和发送 HttpResponse 而无需服务器保留全部内容:

val httpResp : HttpResponse = fileEntityResponse("/foo/log.txt", "UTF8")

关于scala - 如何使用akka http发送文件作为响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49011621/

相关文章:

Akka Streams 入口和导出不匹配

scala - Akka 关闭 TCP actor

Scala Akka Play, future 不会回来

scala-2.11 - 如何从 akka.stream.io.Framing$FramingException 中恢复

scala - 使用 spark-submit 运行时无法加载 com.databricks.spark.csv

scala - 如何从 scala TypeTag 获取通用简单类名?

scala - 为什么我要使用 type T = <type> 而不是 Trait[T]?

scala - Scala/Play 的语法和含义!代码示例

scala - 运行 akka actor 列表以获取消息列表

scala - 播放框架 Scala : Create infinite source using scala akka streams and keep Server sent events connection open on server