Skip to content

Instantly share code, notes, and snippets.

@mrico
Created October 29, 2010 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mrico/653101 to your computer and use it in GitHub Desktop.
Save mrico/653101 to your computer and use it in GitHub Desktop.
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
Copy link
Author

mrico 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