用Akka作为httpresponse的流文件的流内容

发布于 2025-02-06 03:15:32 字数 193 浏览 2 评论 0原文

我正在通过Java FileInputStream读取大文件的一部分,并希望将其内容汇回客户端(以Akka httpresponse的形式)。我想知道这是否可能,以及我将如何做到这一点?

从我的研究中,可以使用EntityStreamingSupport,但仅支持JSON或CSV数据。我将从文件中流式传输原始数据,该数据不会以JSON或CSV的形式流传输。

I am reading parts of large file via a Java FileInputStream and would like to stream it's content back to the client (in the form of an akka HttpResponse). I am wondering if this is possible, and how I would do this?

From my research, EntityStreamingSupport can be used but only supports json or csv data. I will be streaming raw data from the file, which will not be in the form of json or csv.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

橙幽之幻 2025-02-13 03:15:32

假设您使用akka-http和scala,则可以使用getfromfile将整个二进制文件从path将整个二进制文件流式传输到httpresponse之类的

path("download") {
  get {
      entity(as[FileHandle]) { fileHandle: FileHandle =>
      println(s"Server received download request for: ${fileHandle.fileName}")
      getFromFile(new File(fileHandle.absolutePath), MediaTypes.`application/octet-stream`)
      }
    }
 }

。此文件上传/下载往返Akka-http示例:
https://github.com/ pbernet/akka_streams_tutorial/blob/f246BC061A8F5A1ED9F79CCE3F4CCE3F4C52C3C9E1B57A/SRC/MAIN/SCALA/SCALA/AKKKAHTTP/htttpfileecho.scala#l52

堆尺寸。

但是,如果需要,可以这样做手动块:

  val fileInputStream = new FileInputStream(fileHandle.absolutePath)
  val chunked: Source[ByteString, Future[IOResult]] = akka.stream.scaladsl.StreamConverters
    .fromInputStream(() => fileInputStream, chunkSize = 10 * 1024)
      chunked.map(each => println(each)).runWith(Sink.ignore)

Assuming you use akka-http and Scala you may use getFromFile to stream the entire binary file from a path to the HttpResponse like this:

path("download") {
  get {
      entity(as[FileHandle]) { fileHandle: FileHandle =>
      println(s"Server received download request for: ${fileHandle.fileName}")
      getFromFile(new File(fileHandle.absolutePath), MediaTypes.`application/octet-stream`)
      }
    }
 }

Taken from this file upload/download roundtrip akka-http example:
https://github.com/pbernet/akka_streams_tutorial/blob/f246bc061a8f5a1ed9f79cce3f4c52c3c9e1b57a/src/main/scala/akkahttp/HttpFileEcho.scala#L52

Streaming the entire file eliminates the need for "manual chunking", thus the example above will run with limited heap size.

However, if needed manual chunking could be done like this:

  val fileInputStream = new FileInputStream(fileHandle.absolutePath)
  val chunked: Source[ByteString, Future[IOResult]] = akka.stream.scaladsl.StreamConverters
    .fromInputStream(() => fileInputStream, chunkSize = 10 * 1024)
      chunked.map(each => println(each)).runWith(Sink.ignore)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文