Oleg Oleg - 1 month ago 16
Scala Question

akka-http. Generate file and send to client

I need to save string to the text file and send to browser. My route:

def genFileRoute: Route =
path("someresource" / "generate") {
get {
complete( genFile )
}
}


But i have a problem with generator:

def genFile = {
val str = "Hi all! I am a string in future text file"

// Need to write some code here :(
// Something like 'php://output' with headers, but for akka.
}


How to create in-memory text file
file.txt
, without using file system? How to send it to clients browser(download)?

P.S. Sorry for my English, it's not my native.

Answer Source

You want to use Content-Disposition header for this - it allows you to set the file name sent to browser. No need to create a file at all; in your example, the function can return a plain String.

def genFile = {
    val str = "Hi all! I am a string in future text file"

    str
}

Route:

path("someresource" / "generate") {
  get {
    respondWithHeader(`Content-Disposition`(
        ContentDispositionTypes.attachment, Map("filename" -> "somefile.txt"))) {
      complete(genFile)
    }
  }
}