scala - 如何在akka http中发送文件以响应名称
问题描述
我是 AKKA 世界的新手,
我从上面的帖子中获得了如何使用 Akka-HTTP 在 RESTAPI 响应中发送文件的解决方案,但我想为该文件提供名称和扩展名。那么有什么方法可以将文件作为带有文件名和扩展名的响应发送意味着我希望下载的文件在带有 scala 的 Akka-HTTP 中应该有一个带有 .zip 扩展名的名称
解决方案
添加到另一个答案,您可以使用 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'
推荐阅读
- paypal - 设置交易与设置授权
- office-ui-fabric - 将 FluentUI Stack 组件制成的拆分窗格中的宽度固定为 50/50
- wordpress - 显示特定类别标签中的帖子数量
- django - Django RSS 提要:有什么方法可以缓存 M2M 关系以显示在 item_title 中?
- ios - ViewModel 获取新数据时视图未更新
- android - 使用类 App.getContext().getString 的 JUnit 测试中的 Java.lang.NullPointerException
- python - 用字母而不是数字枚举
- aframe - Aframe 字体字体大小和字体类型
- javascript - 来自 .mp4 或 .webm 的网络摄像头录制文件无法在 MacOS Safari 浏览器和 iOS 设备上播放
- javascript - 遍历对象数组并堆叠 Chart JS Bar?