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?
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 */ )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.