2

When I add a new record in a database using a form, I also can upload an image. These two are not linked together; record goes in database and the image goes in an folder on my desktop, so to know which image belongs to which record, I want to put the filename in a column. How do i approach this?

Im using PlayFramework 2.4, Scala, H2 Database and Anorm for my Project

creativename
  • 304
  • 2
  • 16
  • You could save the image with the same name from the PK column, or append the PK value for that record, the the image name. Have you considered saving the image (as a blob/clob) to database as an alternative? – airudah Dec 15 '15 at 13:06
  • @RobertUdah Yes, I did some googling on using BLOB and Scala but looked complicated, probably because im new to Scala and Play – creativename Dec 15 '15 at 13:23
  • On a second thought, storing clobs might not be ideal. This post suggests storing the path to the files as a column in your database which is what you are trying to do anyway. – airudah Dec 15 '15 at 14:36
  • [This post](http://stackoverflow.com/questions/3748/storing-images-in-db-yea-or-nay) – airudah Dec 15 '15 at 14:41
  • ive found a couple examples of how to save the filename in DB and image to a localdirectory, but they are in PHP. I cant seem to find a tutorial or example in Scala. – creativename Dec 15 '15 at 14:41

2 Answers2

2

In your html form you need to have an input tag of file type, something like:

<input type="file" name="picture">

And in your scala method Controller, where you are getting the form submit, something like:

def save = Action(parse.multipartFormData) { request =>
  request.body.file("picture").map { picture =>
    import java.io.File
    val filename = picture.filename
    println(filename)
   Ok("saved")
}
salc2
  • 577
  • 5
  • 14
0

You could retrieve the absolute path of the file like so:

scala> val filePath = getClass.getResource("myImage.png")
filePath: java.net.URI = file:/home/robert/myImage.png
airudah
  • 1,169
  • 12
  • 19