Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Helper for streaming MongoDB GridFS files in lift web applications.
package code.lib
import net.liftweb._
import http._
import util._
import Helpers._
import common._
import mongodb._
import com.mongodb._
import gridfs._
import _root_.java.io.File
object GridFSHelper {
def get(req: Req, filename: String): Box[LiftResponse] = {
MongoDB.use(DefaultMongoIdentifier) ( db => {
val fs = new GridFS(db)
fs.findOne(filename) match {
case file:GridFSDBFile =>
val lastModified = file.getUploadDate.getTime
Full(req.testFor304(lastModified, "Expires" -> toInternetDate(millis + 10.days)) openOr {
val headers =
("Content-Type" -> contentType(filename)) ::
("Pragma" -> "") ::
("Cache-Control" -> "") ::
("Last-Modified" -> toInternetDate(lastModified)) ::
("Expires" -> toInternetDate(millis + 10.days)) ::
("Date" -> nowAsInternetDate) :: Nil
val stream = file.getInputStream
StreamingResponse(
stream,
() => stream.close,
file.getLength,
headers, Nil, 200)
})
case _ => Empty
}
})
}
private def contentType(filename:String) =
LiftRules.context.mimeType(filename) openOr "application/octet-stream"
}
@mrico

This comment has been minimized.

Copy link
Owner Author

commented Oct 29, 2010

Some description can be found here: http://mrico.eu/entry/streaming_files_from_gridfs_wit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.