2013-04-24 56 views
0

我正在使用Play Framework 2.0.4。這裏是我試過的代碼:將圖像存儲到本地系統的指定位置

public static Result save() throws FileNotFoundException { 

    Form<Tenant> tenantForm = form(Tenant.class).bindFromRequest(); 
    Form<Ten> tenForm = form(Ten.class).bindFromRequest(); 
    Long tenantid = tenForm.get().tenant_id; 


    Http.MultipartFormData body = request().body().asMultipartFormData(); 
    Http.MultipartFormData.FilePart picture = body.getFile("logo_url"); 

    if (picture != null) { 
     String fileName = picture.getFilename(); 
     String contentType = picture.getContentType(); 
     File file = picture.getFile(); 
     tenantForm.get().logo_url = file.getPath(); 
     tenantForm.get().save(); 


     return redirect(
      routes.Application.index() 
    ); 
    } else { 
     flash("error", "Missing file"); 
     return redirect(
      routes.Project.ctstenant(0,"name","asc","","",tenantid) 
     ); 
    } 
} 

它會將圖像存儲在臨時文件夾中。我希望它存儲在指定的文件夾中。隨着例子將不勝感激。

感謝您的幫助。

+1

爲什麼不把文件從temp移動到你想要的位置? – Carsten 2013-04-24 11:19:37

回答

0

您可以將文件從TEMP文件夾移動到文件存儲目錄。下面是例子,如何將您上傳的文件:

// define file storage path 
public static final String fileStoragePath = "D:\\filestorage\\"; 

// handle form submit action 
public static Result save() { 

    // bind request logic 
    ... 

    if (picture != null) { 
     String fileName = picture.getFilename(); 
     String contentType = picture.getContentType(); 
     File file = picture.getFile(); 

     // log message to console 
     Logger.info("Original file name = " + fileName + 
     " with Content Type " + contentType); 

     // Rename or move the file to the storage directory 
     if (file.renameTo(new File(fileStoragePath + fileName))) { 
     Logger.info("Success moving file to " + file.getAbsolutePath()); 
     } else { 
     Logger.info("Failed moving file on " + file.getAbsolutePath()); 
     } 

     // save your file name or using blob (it is your choice) 
     ... 
    } 
} 

需要注意的是,在fileStoragePath定義的路徑必須是可用之前成功地移動或重命名上傳的文件。

+0

感謝您的快速回復,我已經完成了它的工作。 – joan 2013-04-24 13:12:17

相關問題