首页 > 解决方案 > 如何在akka http中发送文件以响应名称

问题描述

我是 AKKA 世界的新手,

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

我从上面的帖子中获得了如何使用 Akka-HTTP 在 RESTAPI 响应中发送文件的解决方案,但我想为该文件提供名称和扩展名。那么有什么方法可以将文件作为带有文件名和扩展名的响应发送意味着我希望下载的文件在带有 scala 的 Akka-HTTP 中应该有一个带有 .zip 扩展名的名称

标签: scalaakkahttpresponseakka-http

解决方案


添加到另一个答案,您可以使用 Akka HTTP DSL,如下所示:



  val fileContentsSource: (String, String) => Source[ChunkStreamPart, _] =
    (fileName, enc) =>
      Source
        .fromIterator(() => scala.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)))



  val route: Route = {
    path("file" / Segment) { fileName =>
      complete(fileEntityResponse(fileName, "UTF-8"))
    }
  }

Segment称为 aPathMatcher并将从路由中提取文件名,因此如下调用它

curl --location --request GET 'localhost:PORT/file/filename.txt'

推荐阅读