what is the simplest way to upload a file in mySql db in play 2.0 ?
Uploading files in the database or in a upload folder and then save a link in the database?
I would go for saving the reference in the database and uploading the image somewhere on your webserver. Or, if you persist on saving the image in the DB, save it as a thumb, this wil keep you database size maintainable and your db size acceptable. DBs are in my opinion for data and not assets like images.
Uploading files is documented: http://www.playframework.org/documentation/2.0/JavaFileUpload
How I did it:
View
In the view, make sure you have the correct enctype (this one is based on the twitter bootstrap)
@helper.form(controllers.orders.routes.Task.save, 'class -> "form-horizontal", 'enctype -> "multipart/form-data")
The file input:
@inputFile(taskForm("file1"), '_display -> "Attachment", '_label -> Messages("file"))
In your controller
// 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();
Then iterate trough the attachments and upload them to the upload folder:
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
The code above result in creating a folder and placing the files in that folder. Example:
Folder: T000345
EDIT : 2012-06-23
If you receive the error about the commons package you have to include this in the file 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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With