1

I am a Scala/PlayFramework noob here, so please be easy on me :).

I am trying to create an action (serving a GET request) so that when I enter the url in the browser, the browser should download the file. So far I have this:

def sepaCreditXml() = Action {
  val data: SepaCreditTransfer = invoiceService.sepaCredit()
  val content: HtmlFormat.Appendable = views.html.sepacredittransfer(data)
  Ok(content)
}

What it does is basically show the XML in the browser (whereas I actually want it to download the file). Also, I have two problems with it:

  1. I am not sure if using Play's templating "views.html..." is the best idea to create an XML template. Is it good/simple enough or should I use a different solution for this?

  2. I have found Ok.sendFile in the Play's documentation. But it needs a java.io.File. I don't know how to create a File from HtmlFormat.Appendable. I would prefer to create a file in-memory, i.e. no new File("/tmp/temporary.xml").

EDIT: Here SepaCreditTransfer is a case class holding some data. Nothing special.

Rohit
  • 127
  • 1
  • 10
  • What is the type of `data` returned from `invoiceService`? – Mon Calamari Aug 10 '15 at 16:28
  • It's a case class holding some data. Nothing special. – Rohit Aug 10 '15 at 16:34
  • 1
    Have you had a look at Play's documentation: https://www.playframework.com/documentation/2.4.x/ScalaXmlRequests#Serving-an-XML-response? Or StackOverflow: http://stackoverflow.com/questions/3860750/how-to-download-an-xml-without-the-browser-opening-it-in-another-tab. – Kris Aug 10 '15 at 21:28

1 Answers1

1

I think it's quite normal for browsers to visualize XML instead of downloading it. Have you tried to use the application/force-download content type header, like this?

def sepaCreditXml() = Action {
  val data: SepaCreditTransfer = invoiceService.sepaCredit()
  val content: HtmlFormat.Appendable = views.html.sepacredittransfer(data)
  Ok(content).withHeaders("Content-Type" -> "application/force-download")
}
stefanobaghino
  • 11,253
  • 4
  • 35
  • 63
  • 1
    @Rohit Good, just make it sure that forcing the download really is what you want to do. Keep in mind that you can force download from the client as well by adding the ```download[="filename"]``` attribute to the ```a``` tag of the link. This would preserve the proper MIME type for other clients when asking for the resource from the server. – stefanobaghino Aug 11 '15 at 12:31