Last active
December 20, 2015 12:09
-
-
Save yangbajing/6128521 to your computer and use it in GitHub Desktop.
使用lift restful 实现资源下载功能
This file contains hidden or 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 com.cqccn.iams.server | |
import java.util.Locale | |
import org.joda.time.{DateTimeZone, DateTime} | |
import org.joda.time.format.DateTimeFormat | |
import net.liftweb.common.Full | |
import net.liftweb.http.rest.RestHelper | |
import net.liftweb.http._ | |
object RestDemo extends RestHelper { | |
serve { | |
case req@Req("api" :: "download" :: "image" :: id :: Nil, suffix, GetRequest) => | |
try | |
req.ifModifiedSince match { | |
case Full(date) if !MResource.isModified(id, date) => // 数据库中资源未更新 | |
NotModifiedResponse | |
case _ => // 从数据库中获取资源 | |
val lastModified = DateTime.now | |
ImageResponse(Array(), "image/jpeg", 0L, lastModified) | |
} | |
catch { | |
case e: Exception => | |
InternalServerErrorResponse() | |
} | |
} | |
val formatInternetDate = | |
DateTimeFormat.forPattern("EEE, d MMM yyyy HH:mm:ss 'GMT'").withLocale(Locale.US).withZone(DateTimeZone.UTC) | |
} | |
case class ImageResponse(bytes: Array[Byte], contentType: String, size: Long, lastModified: DateTime) extends LiftResponse { | |
val headers = | |
List("Content-Type" -> contentType, "Content-Length" -> size.toString, "Last-Modified" -> RestDemo.formatInternetDate.print(lastModified)) | |
val toResponse = | |
InMemoryResponse(bytes, headers, Nil, 200) | |
} | |
case object NotModifiedResponse extends LiftResponse with HeaderDefaults { | |
val toResponse = | |
InMemoryResponse(Array(), headers, cookies, 304) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment