《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

猜你喜欢

转载自blog.csdn.net/weixin_34332905/article/details/93057219