Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any sample to store and retrieve image on mongodb using gridfs, scala and playframework2

I have a model

case class Person(
  _id: ObjectId = new ObjectId,
  empno: String,
  name: String,
  picture: String
)

I'm a bit lost on how do I handle the picture upload on the form, controller and view. Appreciate help for sample or point me to the correct direction.

like image 950
William Avatar asked Dec 29 '25 22:12

William


1 Answers

This answer uses GridFS, however you may do what you want with file in upload method.

Form view:

@helper.form(routes.Application.upload, 'enctype -> "multipart/form-data") {
  @helper.inputFile(form("photo"))
  <button type="submit">upload</button>
}

Display view:

<img src='@routes.Application.getPhoto(fileId)'/>

Controller:

def upload = Action(parse.multipartFormData) { request =>
  request.body.file("photo") match {
    case Some(photo) =>
      val gridFs = salat.gridFS("photos")
      val uploadedFile = gridFs.createFile(photo.ref.file)
      uploadedFile.contentType = photo.contentType.orNull
      uploadedFile.save()
      Ok(...)
    case None => BadRequest("no photo")
  }
}

def getPhoto(file: ObjectId) = Action {
  import com.mongodb.casbah.Implicits._

  val gridFs = salat.gridFS("photos")

  gridFs.findOne(Map("_id" -> file)) match {
    case Some(f) => SimpleResult(
      ResponseHeader(OK, Map(
        CONTENT_LENGTH -> f.length.toString,
        CONTENT_TYPE -> f.contentType.getOrElse(BINARY),
        DATE -> new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", java.util.Locale.US).format(f.uploadDate)
      )),
      Enumerator.fromStream(f.inputStream)
    )

    case None => NotFound
  }
}

Routes:

GET /upload controllers.Application.upload
GET /photos/:file controllers.Application.getPhoto(file: ObjectId)
like image 150
kriomant Avatar answered Jan 01 '26 18:01

kriomant