Created
October 29, 2010 07:46
-
-
Save mrico/653101 to your computer and use it in GitHub Desktop.
Helper for streaming MongoDB GridFS files in lift web applications.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Some description can be found here: http://mrico.eu/entry/streaming_files_from_gridfs_wit