Last active
December 15, 2015 11:29
-
-
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.
This file contains hidden or 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
| // 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) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
very neat. what version of play was this written against?