将图像存储到本地系统的指定位置

问题描述:

我正在使用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

您可以将文件从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