ScalaBoy
ScalaBoy

Reputation: 85

Display image from MongoDB using reactivemongo in Play2 Scala

I'm passing this List to a Play2 template:

files: Option[List[(String, reactivemongo.api.gridfs.ReadFile[reactivemongo.bson.BSONValue])]])

how to do I pull the first image from the List and render that image to the html tag

<img src=" ">

Any help will be GREAT :)

Thanks Danny

Upvotes: 3

Views: 1038

Answers (1)

huynhjl
huynhjl

Reputation: 41646

From looking at the reactive mongo demo app, it seems you have to add a route for serving the image from gridfs. Look at the route file and the controller, that example shows how to serve attachments. So your case might look like that:

In the route file:

GET     /img/:id            controllers.Images.getImg(id)

And in the Images controller:

def getImg(id: String) = Action {
  Async {
    import reactivemongo.api.gridfs.Implicits.DefaultReadFileReader
    val file = gridFS.find(BSONDocument("_id" -> new BSONObjectID(id)))
    serve(gridFS, file)
  }
}

Then in your template:

@if(files.isDefined) {
    @files.get.map { file =>
    <img src="@routes.Images.getImg(file._1)"/>
  }
}

Upvotes: 3

Related Questions