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:
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.
Define the POST request in routes in order to call uploadFile action.
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.
Find the complete code here on Github
5 thoughts on “Play Framework : Uploading a file to server2 min read”
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’).
Thank you so much for a such a nice blog on play but can you please help me to in fileuploading in java on playframework.
without refreshing page how to upload file , this code is refreshing all page so please suggest me code for without refreshing page.
/upload exists in routes. I want to understand that /upload is called by submit button by default or have we defined it somewhere?
Also, when I select a file and click submit button, I get the following error:
[warn] p.filters.CSRF – [CSRF] Check failed because no or invalid token found in body for /upload
[warn] p.filters.CSRF – [CSRF] Check failed with NoTokenInBody for /upload
How to resolve these errors?
Comments are closed.