Play in action – Upload file

Play Framework - Build Modern & Scalable Web Apps with Java and Scala

                   In this article, we will see how to save student information along with the student profile pic. Let us design a form to collect student information.

Student Form With Profile Picture Upload

In the above form, we have text fields and “file” upload field to upload student picture. So the form will send a post request to the REST service with student information and the image. In the code, we are going to get the student information as JSON and the image from the request body. The sample code is given below.

* This method saves the student.
* @return - The available students in map with JSON representation
public Result saveStudent() {
    JsonNode json = Json.parse(request().body().asMultipartFormData().asFormUrlEncoded().get("json")[0]);
    MultipartFormData formData = request().body().asMultipartFormData();
    File logo = null;
    if (formData != null) {
       FilePart logoFilePart = formData.getFile("student_pic");
       if (logoFilePart != null) {
          logo = logoFilePart.getFile();
          Logger.debug("File Uploaded Name ::"+logoFilePart.getFilename());
   Logger.debug("json" + json.toString());
   Student st = new Student();
   students.put(json.findPath("userName").textValue(), st);
   Logger.debug("The aviable students size is " + students.size());
   return ok(Json.toJson(students.values()));

The sample request made to save the student information along with the profile pic is shown below.
Student Save Information Request

The source code created as part of the above example is available in GitHub.

Code to upload file using Play framework

I am Siva Prasad Rao Janapati. Working as Technical Architect. Has hands on experience on ATG Commerce(DAS/DPS/DCS), Mozu commerce, Broadleaf Commerce, Java, JEE, Spring, Play, JPA, Hibernate, Velocity, JMS, Jboss, Weblogic,Tomcat, Jetty, Apache, Apache Solr, Spring Batch, JQuery, NodeJS, SOAP, REST, MySQL, Oracle, Mongo DB, Memcached, HazelCast, Git, SVN, CVS, Ant, Maven, Gradle, Amazon Web services, Rackspace, Quartz, JMeter, Junit, Open NLP, Facebook Graph,Twitter4J, YouTube Gdata, Bazzarvoice,Yotpo, 4-Tell, Alatest, Shopzilla, Linkshare. I have hands on experience on open sources and commercial technologies.

Tagged with: ,
Posted in Frameworks, Play

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.



Java Code Geeks
Java Code Geeks
%d bloggers like this: