5

Basically I want to allow a user to download a csv file from the server. Assume the CSV file already exists on the server. A API endpoint is exposed via GET /export. How do I stream the file from Akka HTTP server to client? This is what I have so far...

Service:

def export(): Future[IOResult] = {
    FileIO.fromPath(Paths.get("file.csv"))
      .to(Sink.ignore)
      .run()
}

Route:

pathPrefix("export") {
  pathEndOrSingleSlash {
    get {
      complete(HttpEntity(ContentTypes.`text/csv`, export())
    }
  }
}
perry
  • 85
  • 5

1 Answers1

6

The Akka-Stream API allow you to create an entity directly out of a Source[ByteString, _], so you can do something along the lines of

pathPrefix("export") {
  pathEndOrSingleSlash {
    get {
      complete(HttpEntity(ContentTypes.`text/csv(UTF-8)`, FileIO.fromPath(Paths.get("file.csv")))
    }
  }
}

Note that this way your server code will not need to ingest the whole CSV file in memory before sending it over the wire. The file contents will be sent over in a backpressure-enabled stream. More on this here.

Stefano Bonetti
  • 8,973
  • 1
  • 25
  • 44
  • Thanks for that! Next step for me is streaming the file to client as the rows are written without having to create a temporary file on the server first. – perry Dec 15 '16 at 16:07
  • @perry Can you please share your approach on what you did next ? – oblivion Feb 03 '18 at 15:34
  • 1
    `def export(): Source[ByteString, _] = Source.fromPublisher(db.stream(things.result.transactionally.withStatementParameters(fetchSize = 1000)))` Where `things` is a a TableQuery – perry Feb 04 '18 at 16:18