如何使用 akka http 发送文件作为响应?
How to send a file as a response using 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.
)
}
val str2 = scala.io.Source.fromFile("/tmp/t.log", "UTF8").mkString
val str = Source.single(ByteString(str2))
HttpResponse(entity = HttpEntity.Chunked.fromData(ContentTypes.`application/octet-stream`, str))
如果文件可能很大,那么您不希望在将其发送给客户端之前将全部内容消耗到内存中。这是通过纯基于流的解决方案解决的:
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")
Akka Http 路由
pathSingleSlash {
get {
complete(HttpEntity.fromFile(MediaTypes.`application/zip`, new File(s"/home/shivam/sample.zip"))
}
}
Curl 请求
curl --output sample.zip http://localhost:8080/
复制自HttpEntity.scala
/**
* Returns either the empty entity, if the given file is empty, or a [[HttpEntity.Default]] entity
* consisting of a stream of [[akka.util.ByteString]] instances each containing `chunkSize` bytes
* (except for the final ByteString, which simply contains the remaining bytes).
*
* If the given `chunkSize` is -1 the default chunk size is used.
*/
我对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.
)
}
val str2 = scala.io.Source.fromFile("/tmp/t.log", "UTF8").mkString
val str = Source.single(ByteString(str2))
HttpResponse(entity = HttpEntity.Chunked.fromData(ContentTypes.`application/octet-stream`, str))
如果文件可能很大,那么您不希望在将其发送给客户端之前将全部内容消耗到内存中。这是通过纯基于流的解决方案解决的:
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")
Akka Http 路由
pathSingleSlash {
get {
complete(HttpEntity.fromFile(MediaTypes.`application/zip`, new File(s"/home/shivam/sample.zip"))
}
}
Curl 请求
curl --output sample.zip http://localhost:8080/
复制自HttpEntity.scala
/**
* Returns either the empty entity, if the given file is empty, or a [[HttpEntity.Default]] entity
* consisting of a stream of [[akka.util.ByteString]] instances each containing `chunkSize` bytes
* (except for the final ByteString, which simply contains the remaining bytes).
*
* If the given `chunkSize` is -1 the default chunk size is used.
*/