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)
        );
    }
}

它将图像存储在临时文件夹中。我希望它存储在指定的文件夹中。有了这个例子将不胜感激。

谢谢您的帮助。

4

1 回答 1

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必须在成功移动或重命名上传文件之前可用。

于 2013-04-24T11:49:45.403 回答