This code will save your file in the data / attachments directory of your project:
Model
package models; import play.db.jpa.Blob; import play.db.jpa.Model; import javax.persistence.Entity; @Entity public class MyApp extends Model { public String name; public Blob file; }
Template
#{form action:@create(), enctype:'multipart/form-data'} #{crud.form /} <label for="uploadFile">File</label> <input type="file" id="uploadFile" name="myapp.file" /> <p class="crudButtons"> <input type="submit" name="_save" value="&{'crud.save', type.modelName}" /> <input type="submit" name="_saveAndContinue" value="&{'crud.saveAndContinue', type.modelName}" /> </p> #{/form}
controller
package controllers import play.*; import play.mvc.*; import java.util.*; import models.*; /* Custom controller that extends * controller from CRUD module. */ public class MyController extends CRUD { // ... // Will save your object public static void create(MyApp object) { /* Get the current type of controller and test it on non-empty */ ObjectType type = ObjectType.get(getControllerClass()); notFoundIfNull(type); /* We perform validation of the generated crud module form fields */ validation.valid(object); if (validation.hasErrors()) { renderArgs.put("error", Messages.get("crud.hasErrors")); try { render(request.controller.replace(".", "/") + "/blank.html", type, object); } catch (TemplateNotFoundException e) { render("CRUD/blank.html", type, object); } } /* Save our object into db */ object._save(); /* Show messages */ flash.success(Messages.get("crud.created", type.modelName)); if (params.get("_save") != null) { redirect(request.controller + ".list"); } if (params.get("_saveAndAddAnother") != null) { redirect(request.controller + ".blank"); } }
As stated above, you simply supplement the crud form with your field and override the crud "create" method. The same thing can be done to update the record. You can change the data / attachment directory in application.conf:
application.conf
# ...
See http://www.lunatech-research.com/playframework-file-upload-blob for details
source share