Skip to content

Instantly share code, notes, and snippets.

@flightonary
Created April 20, 2015 13:59
Show Gist options
  • Save flightonary/32b40c9fd5c9d2d59d49 to your computer and use it in GitHub Desktop.
Save flightonary/32b40c9fd5c9d2d59d49 to your computer and use it in GitHub Desktop.
ByteContentResult in Play Framework
package controllers
import play.api.mvc._
import utilities._
object Application extends Controller with ResultUtility {
object DataStore {
val filename = "hoge.gif"
val contentType = "image/gif"
val blobdata = "data".getBytes
}
def index = Action { request =>
Ok.withByteContent(DataStore.contentType, Some(DataStore.filename), DataStore.blobdata)
}
}
package utilities
import play.api.mvc.SimpleResult
import play.api.libs.iteratee.Enumerator
import play.api.http.HeaderNames
trait ResultUtility {
implicit class ByteContentResult(self: SimpleResult) {
def withByteContent(contentType: String, filename: Option[String], content: Array[Byte]): SimpleResult = {
val newHeader = self.header.copy(
headers = self.header.headers
++ Map(HeaderNames.CONTENT_LENGTH -> content.length.toString, HeaderNames.CONTENT_TYPE -> contentType)
++ filename.map { fn =>
Map(HeaderNames.CONTENT_DISPOSITION -> ("""attachment; filename="%s"""".format(fn)))
}.getOrElse(Map.empty))
SimpleResult(newHeader, Enumerator(content))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment