Upload the CRUD file to the framework

Does anyone know a way to add a file to upload to a CRUD form? So far I have this part:

#{form action:@save(object._key()), enctype:'multipart/form-data'} #{crud.form} #{crud.custom 'file'} <label for="uploadFile"> File </label> <input type="file" id="uploadFile" name="uploadFile" /> #{/crud.custom} #{/crud.form} <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} 

But I do not know how to write a controller method to handle loading. And I do not want to store the file in db as blob, I do not want to do this on the file system.

+1
source share
2 answers

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

 # ... # Store path for Blob content attachments.path=data/attachments # ... 

See http://www.lunatech-research.com/playframework-file-upload-blob for details

+3
source

Source: https://habr.com/ru/post/1387036/


All Articles