播放框架CRUD文件上传

时间:2011-12-07 16:12:19

标签: file-upload playframework crud

任何人都知道将文件上传添加到Play的CRUD表单的方法吗?到目前为止,我有一个像这样的观点部分:

   #{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}

但我不知道如何编写控制器方法来处理上传。 而且我不想将文件作为blob存储在db中,我不想在文件系统上。

1 个答案:

答案 0 :(得分:3)

此代码会将您的文件保存到项目的“data / attachments”目录中:

模型

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;

}

模板

#{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}

控制器

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");
    }

}

如上所述,您只需通过自己的字段补充crud表单并覆盖crud方法“create”。更新记录也可以这样做。 您可以在application.conf中更改“data / attachments”目录:

application.conf

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

有关详细信息,请参阅http://www.lunatech-research.com/playframework-file-upload-blob