Folks,

Lately there's been a bunch of chatter on the list about image upload and
figuring out how to put the image files in the right place to serve them
again.

I've written a simple example of image uploading, storing the image in the
RDBMS and then serving the image.  You can find the code at:
http://github.com/dpp/imagine/

The file upload snippet is very simple:

class DoUpload {
  private def saveFile(fp: FileParamHolder): Unit = {
    fp.file match {
      case null =>
      case x if x.length == 0 =>
      case x =>
        val blob = ImageBlob.create.image(x).saveMe
        ImageInfo.create.name
(fp.fileName).mimeType(fp.mimeType).blob(blob).saveMe
        S.notice("Thanks for the upload")
        S.redirectTo("/")
    }
  }

  def render(in: NodeSeq): NodeSeq =
  bind("upload", in, "file" -> SHtml.fileUpload(saveFile _))

}


If the blob is uploaded, it's put in a row in ImageBlob and an ImageInfo row
is created to store the name and mime type.  There are two different rows so
that one doesn't have to pull the whole blob back when you're checking for
the upload date.

Serving the image is similarly concise:

  def serveImage: LiftRules.DispatchPF = {
    case req @ Req("images" :: _ :: Nil, _, GetRequest) if
findFromRequest(req).isDefined =>
      () => {
        val info = findFromRequest(req).open_! // open is valid here because
we just tested in the guard

        // Test for expiration
        req.testFor304(info.date, "Expires" -> toInternetDate(millis +
30.days)) or
        // load the blob and return it
        info.blob.obj.map(blob => InMemoryResponse(blob.image,
List(("Last-Modified", toInternetDate(info.date.is)),

 ("Expires", toInternetDate(millis + 30.days)),

 ("Content-Type", info.mimeType.is)), Nil,  200))
      }
  }


If the request matches /images/xxx where xxx is a name in the ImageInfo
table, check to see if we can return a 304 (not modified).  If not, we pull
the blob from the database and return it.

I hope this helps folks who are looking to manage and serve images.

Thanks,

David

-- 
Lift, the simply functional web framework http://liftweb.net
Beginning Scala http://www.apress.com/book/view/1430219890
Follow me: http://twitter.com/dpp
Surf the harmonics

--

You received this message because you are subscribed to the Google Groups 
"Lift" group.
To post to this group, send email to lift...@googlegroups.com.
To unsubscribe from this group, send email to 
liftweb+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/liftweb?hl=en.


Reply via email to