I would like to store images uploaded as user content in GridFS
in a Scala Play 2 application. How can I restore the binary file from the GridFSDBFile
that GridFS.findOne
gives me?
Asked
Active
Viewed 443 times
1 Answers
0
You could serve the file by streaming its contents and setting the correct http headers - an example of doing so is here.
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.UK).format(f.uploadDate)
)),
Enumerator.fromStream(f.inputStream)
)
case None => NotFound
}
}
However, this often isn't the most performant option for serving files. File systems are designed to do that or putting the url root behind a cache - eg varnish or deploying to cdn is often a better choice.