《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

转载于:https://www.cnblogs.com/JoannaQ/p/3646889.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值