Created
April 20, 2015 13:59
-
-
Save flightonary/32b40c9fd5c9d2d59d49 to your computer and use it in GitHub Desktop.
ByteContentResult in Play Framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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