I'm currently using the following with Play2/Scala using the FileUploader Javascript utility to upload a file to my server:
def fileUploader = Action(parse.multipartFormData) { request =>
request.body.file("qqfile").map { picture =>
import java.io.File
val filename = picture.filename
val contentType = picture.contentType
picture.ref.moveTo(new File("/tmp",filename))
Ok(Json.toJson(Map( "success" -> "true" )))
}.getOrElse {
Ok(Json.toJson(Map( "error" -> "error occured")))
}
}
I'm only dealing with small files (<10MB) and I want to use casbah to write those files directly into a Mongo Document or GridFS using the Mongo drivers. I realize I could just read the saved file from disk, but is there a way to handle this all from memory without buffering the file on disk first?
The play documentation here recommends writing a custom BodyParser (http://www.playframework.com/documentation/2.1.0/ScalaFileUpload) but there doesn't seem to be any documentation on how to go about writing one. It wasn't clear how the API/implementation worked from the Scaladocs. I tried looking for the MultiPartFormData source code to see how it worked, but I can't seem to find it in their Git repo:
https://github.com/playframework/Play20/tree/master/framework/src/play/src/main/scala/play/api/mvc
I've searched quite a bit, but can't seem to find a good example.
Untested The
Multipart
object of theBodyParsers
does a lot of work for us. The first thing we need to do write a handler for theFilePart
. I assume here that you want the file parts anArray[Byte]
.The next step is to define your body parser:
Then, in order to use it, specify it at you
Action
:Some types and methods in the above pieces of code are a bit hard to find. Here is a complete list of imports in case you need it:
The Play API has changed a decent amount since this was posted. I had a similar use case where I didn't want a temp file and translated the above into the following, which seems to work with Play 2.6 in case anyone needs this:
Using it in a controller make sure you inject
PlayBodyParsers
and provide anExecutionContext
, imports etc below: