《Play for Java》學習筆記(六)文件上傳file upload

1、 Play中標準方法html

使用表單form和multipart/form-data的content-type類型。this

1.Formspa

@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)scala

2. Upload actioncode

@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直接上傳文件orm

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

說明: 此時不用編譯爲multipart/form-data類型htm

2、案例——(項目源碼)
blog

1. 爲product模型添加picture成員變量ip

2. 在details.scala.html中加入代碼element

@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

相關文章
相關標籤/搜索