Ophelia
Ophelia

Reputation: 569

Scala Playframework send file

I have a string of data, which I get from data in my database. I want to send it to the user, but without creating a local copy of the file, something like

Ok(MyString).as("file/csv") 

But it is not working. How can I do it?

Upvotes: 5

Views: 2654

Answers (1)

Michael Zajac
Michael Zajac

Reputation: 55569

You can do this by using chunked with an Enumerator. I've also used withHeaders to specify the content type and disposition of the Result to "attachment", so that the client will interpret it as a file to download (rather than opening in the browser itself).

import play.api.libs.iteratee.Enumerator

val myString: String = ??? // the String you want to send as a file

Ok.chunked(Enumerator(myString.getBytes("UTF-8")).andThen(Enumerator.eof))
  .withHeaders(
     "Content-Type" -> "text/csv",
     "Content-Disposition" -> "attachment; filename=mystring.csv"
  )

This might not compile right away, depending on the types you're getting from the database.

Come to think of it, this should also work (without the Enumerator):

 Ok(myString).withHeaders( /* headers from above */ )

Upvotes: 6

Related Questions