我正在使用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)
);
}
}
它会将图像存储在临时文件夹中。我希望它存储在指定的文件夹中。通过这个例子将不胜感激。
感谢您的帮助。
答案 0 :(得分: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
上定义的路径必须可用。