Skip to content

Instantly share code, notes, and snippets.

@yllan
Last active December 15, 2015 11:29
Show Gist options
  • Select an option

  • Save yllan/5253001 to your computer and use it in GitHub Desktop.

Select an option

Save yllan/5253001 to your computer and use it in GitHub Desktop.
How to calculate the sha-1 hash when receiving uploaded files using BodyParser in PlayFramework so that you don't need to open the file and read the content again. Also an example of how to process stream data in Play using Iteratee.
// import java.io._
// import java.security._
// import play.api.libs.iteratee._
def sha1FileParser(to: File): BodyParser[(String, File)] = BodyParser((header: RequestHeader) ⇒ {
Iteratee.fold[Array[Byte], (MessageDigest, FileOutputStream)](MessageDigest.getInstance("SHA-1"), new FileOutputStream(to)) { case ((md, os), data) ⇒
md.update(data)
os.write(data)
(md, os)
} mapDone { case (md, os) ⇒
os.close
Right((md.digest.map("%02x".format(_)).mkString, to))
}
})
def upload = Action(sha1FileParser(new File("/tmp/upload"))) { request ⇒
val (sha1: String, file: File) = request.body
Logger.info(sha1)
Ok("sha1 is: " + sha1)
}
@nacmacfeegle

Copy link
Copy Markdown

very neat. what version of play was this written against?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment