Download csv file using Play Framework?

I want to add a simple button to my application that, when clicked, will trigger an action that will create a csv file from the two lists that I have, and upload it to the user's computer.

This is my action:

def createAndDownloadFile = Action {

    val file = new File("newFile.csv")

    val writer = CSVWriter.open(file)

    writer.writeAll(List(listOfHeaders, listOfValues))

    writer.close()

    Ok.sendFile(file, inline = false, _ => file.getName)
  }

but now it works for me, the file does not load from the browser ...

im, expecting the file to load by the browser, I thought I Ok.sendFileshould do the trick.

thank!

+4
source share
1 answer

You can use Enumerators and threads for this. It should work as follows:

val enum   = Enumerator.fromFile(...)
val source = akka.stream.scaladsl.Source.fromPublisher(play.api.libs.streams.Streams.enumeratorToPublisher(enum))
Result(
  header = ResponseHeader(OK, Map(CONTENT_DISPOSITION → "attachment; filename=whatever.csv.gz")),
  body = HttpEntity.Streamed(source.via(Compression.gzip), None, None)
)

gzip. .via(Compression.gzip), .

-1

Source: https://habr.com/ru/post/1678348/


All Articles