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.
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(); st.setUserName(json.findPath("userName").textValue()); st.setFirstName(json.findPath("firstName").textValue()); st.setLastName(json.findPath("lastName").textValue()); st.setAge(json.findPath("age").textValue()); 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.
The source code created as part of the above example is available in GitHub.
Leave a Reply