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

Sak*_*ham 2 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.
    )
}
Run Code Online (Sandbox Code Playgroud)

Ram*_*gil 5

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

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)))
Run Code Online (Sandbox Code Playgroud)

现在,您可以创建并发送HttpResponse,而无需服务器保留所有内容:

val httpResp : HttpResponse = fileEntityResponse("/foo/log.txt", "UTF8")
Run Code Online (Sandbox Code Playgroud)