上传数据库或上传文件夹中的文件,然后在数据库中保存链接?
我会去将参考保存在数据库中并将图像上传到网络服务器上的某个位置。或者,如果您坚持将图像保存在数据库中,请将其另存为拇指,这将使您的数据库大小保持可维护且数据库大小可接受。在我看来,数据库是用于数据的,而不是图像等资产。
上传文件有记录:http://www.playframework.org/documentation/2.0/JavaFileUpload http://www.playframework.org/documentation/2.0/JavaFileUpload
我是怎么做到的:
View
在视图中,确保您拥有正确的enctype
(这个是基于twitter bootstrap)
@helper.form(controllers.orders.routes.Task.save, 'class -> "form-horizontal", 'enctype -> "multipart/form-data")
文件输入:
@inputFile(taskForm("file1"), '_display -> "Attachment", '_label -> Messages("file"))
在你的控制器中
// first i get the id of the task where I want to attach my files to
MultipartFormData body = request().body().asMultipartFormData();
List<FilePart> resourceFiles = body.getFiles();
然后遍历附件并将其上传到上传文件夹:
for (int i = 0; i < resourceFiles.size(); i++) {
FilePart picture = body.getFile(resourceFiles.get(i).getKey());
String fileName = picture.getFilename();
File file = picture.getFile();
File destinationFile = new File(play.Play.application().path().toString() + "//public//uploads//"
+ newTask.getCode() + "//" + i + "_" + fileName);
System.out.println(play.Play.application().path());
System.out.println(file.getAbsolutePath());
try {
FileUtils.copyFile(file, destinationFile);
TaskDocument taskDocument = new TaskDocument(newTask.description, "/assets/uploads/"
+ newTask.getCode() + "/" + i + "_" + fileName, loggedInUsr, newTask);
taskDocument.save();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Result
上面的代码会创建一个文件夹并将文件放入该文件夹中。例子:
文件夹:T000345
- 0_橙色.png
- 1_苹果.png
- 2_pear.png
编辑 : 2012-06-23
如果您收到有关 commons 包的错误,您必须将其包含在文件中Build.scala
:
val appDependencies = Seq(
// Add your project dependencies here,
"mysql" % "mysql-connector-java" % "5.1.18",
"org.specs2" %% "specs2" % "1.9" % "test",
"commons-io" % "commons-io" % "2.2") // at least this one must be present!