In order to upload a file to server we used to use the form with multipart/form-data encoding. File upload is very easy with Play. Use a multipart/form-data encoded request to post files to the server, and then use the java.io.File type to retrieve the file object.
Let us see how we can handle the file upload within Play framework.
Writing an HTML form:
@helper.form(action = routes.Application.uploadFile, 'enctype -> "multipart/form-data") {
<input type="file" name="fileUpload">
<p>
<input type="submit" value="Upload">
</p>
}
Notice that we’ve given the name “fileUpload” to our upload control.We’ll use same name in our Controller Action. We’ve created the form action as well which is uploadFile in our “Application” controller.
Now define the uploadFile action using a multipartFormData body parser.
def uploadFile = Action(parse.multipartFormData) { request =>
request.body.file("fileUpload").map { video =>
val videoFilename = video.filename
val contentType = video.contentType.get
video.ref.moveTo(new File("/home/neelkanth/Desktop/" + video.filename))
}.getOrElse {
Redirect(routes.Application.index)
}
Ok("File has been uploaded")
}
Define the POST request in routes in order to call uploadFile action.
GET / controllers.Application.index POST /upload controllers.Application.uploadFile
GET call will render the view of our application and the POST /upload will upload our file by calling the action defined above.
The Application controller.
import play.api._
import play.api.mvc._
import java.io.File
object Application extends Controller {
def index = Action {
Ok(views.html.index("File Upload In Play"))
}
/**
* uploadFile action definition
*/
def uploadFile = Action(parse.multipartFormData) { request =>
request.body.file("fileUpload").map { video =>
val videoFilename = video.filename
val contentType = video.contentType.get
video.ref.moveTo(new File("/home/neelkanth/Desktop/" + video.filename))
}.getOrElse {
Redirect(routes.Application.index)
}
Ok("File has been uploaded")
}
}
Find the complete code here on Github






Even in such small tutorials I suggest taking more care about security – do not use a name of the file in your target path (Application:18: ‘”/home/neelkanth/Desktop/” + video.filename’).