• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Joanna Qian
Stay Hungry, Stay Foolish!
博客园    首页    新随笔    联系   管理    订阅  订阅
《Play for Java》学习笔记(六)文件上传file upload

一、 Play中标准方法

使用表单form和multipart/form-data的content-type类型。

1.Form

@form(action = routes.Application.upload, 'enctype -> "multipart/form-data") {
    <input type="file" name="picture">
    <p><input type="submit"></p>
}

说明: HTTP method for the form have to be POST (not GET)

2. Upload action

@BodyParser.Of(value = BodyParser.Text.class, maxLength = 10 * 1024)
  public static Result upload() {
  MultipartFormData body = request().body().asMultipartFormData();
  FilePart picture = body.getFile("picture");
  if (picture != null) {
    String fileName = picture.getFilename();
    String contentType = picture.getContentType(); 
    File file = picture.getFile();
    return ok("File uploaded");
  } else {
    flash("error", "Missing file");
    return redirect(routes.Application.index());    
  }
}

3. 如果想使用Ajax直接上传文件

public static Result upload() {
  File file = request().body().asRaw().asFile();
  return ok("File uploaded");
}

说明: 此时不用编译为multipart/form-data类型

二、案例——(项目源码)

1. 为product模型添加picture成员变量

2. 在details.scala.html中加入代码

@main("Product form") {
<h1>Product form</h1>
  @helper.form(action = routes.Products.save(),'enctype -> "multipart/form-data"){  //The HTML form is now multipart
    <fieldset>
      <legend>Product (@productForm("name").valueOr("New"))</legend>
      @helper.inputText(productForm("ean"), '_label -> "EAN", '_help -> "Must be exaclty 13 numbers.")
      @helper.inputText(productForm("name"),'_label -> "Name")
      @helper.inputText(productForm("date"),'_label -> "Date")
      @helper.inputText(productForm("peremptionDate"),'_label -> "Peremption date")    
      @helper.textarea(productForm("description"), '_label -> "Description")   
      @helper.inputFile(productForm("picture"), '_label -> "Please choose files")    //Our input file HTML element
      @if(!productForm("picture").valueOr("").isEmpty()) { //The img HTML tag used to display the picture 
      <span> 
        <!-- <img style="position:relative; left:50px;height:80px" src="/picture/@productForm("ean").value"> --> 
        <img style="position:relative; left:50px;height:80px" src="@routes.Products.picture(productForm("ean").value)"/> 
      </span>
    }
......
 }
}

3. 在Products Controller中加入以下代码

public static Result save() {
    Form<Product> boundForm = productForm.bindFromRequest();   //Create a Form  object from the current request
     ......
    Product product = boundForm.get();    //Bind the Product object from the form 
    MultipartFormData body = request().body().asMultipartFormData();
    //Binds form as a multipart form so we can access submitted file
    //Requests picture FilePart
    //---this should match the name attribute of the input file in our form ( 就文件上传所在的input的name必须是picture) 
  MultipartFormData.FilePart part = body.getFile("picture"); 
  if(part != null) { 
    File picture = part.getFile(); 
    try { 
      product.picture = Files.toByteArray(picture); //A utility method copies file contents to a byte[] 
    } catch (IOException e) { 
      return internalServerError("Error reading file upload");
        }
    }
    ......
    product.save();    //Save or update our current Product object
    flash("success", String.format("Successfully added product %s", product));
    return redirect(routes.Products.list(1));   //Redirect to our “view all products” page
  }
//新建的picture action
public static Result picture(String ean) {
    final Product product = Product.findByEan(ean);
    if(product == null) return notFound();
        return ok(product.picture);
}

3. 在routes中加入以下代码

GET   /picture/:ean       controllers.Products.picture(ean: String)

参考:  http://www.playframework.com/documentation/2.0/JavaFileUpload

posted on 2014-04-05 04:02  Joanna Qian  阅读(1569)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3