我想我正確地將圖像保存到Postgres,但得到意想不到的結果,試圖加載圖像。我真的不知道錯誤是保存還是加載。使用Anorm(Scala/PlayFramework 2)在Postgres中保存/加載圖像
這裏是保存圖像我ANORM代碼:
def storeBadgeImage(badgeHandle: String, imgFile: File) = {
val cmd = """
|update badge
|set img={imgBytes}
|where handle = {badgeHandle}
"""
var fis = new FileInputStream(imgFile)
var imgBytes: Array[Byte] = Resource.fromInputStream(fis).byteArray
// at this point I see the image in my browser if I return the imgBytes in the HTTP response, so I'm good so far.
DB.withConnection { implicit c =>
{
try {
SQL(cmd stripMargin).on("badgeHandle" -> badgeHandle, "imgBytes" -> imgBytes).executeUpdate() match {
case 0 => "update failed for badge " + badgeHandle + ", image " + imgFile.getCanonicalPath
case _ => "Update Successful"
}
} catch {
case e: SQLException => e.toString()
}
}
}
}
...我得到「更新成功的」,所以我推測保存在工作(我可能是錯的)。這裏是我的加載圖像代碼:
def fetchBadgeImage(badgeHandle: String) = {
val cmd = """
|select img from badge
|where handle = {badgeHandle}
"""
DB.withConnection { implicit c =>
SQL(cmd stripMargin).on("badgeHandle" -> badgeHandle)().map {
case Row(image: Array[Byte]) => {
"image = " + image
}
case Row(Some(unknown: Any)) => {
println(unknown + " unknown type is " + unknown.getClass.getName) //[[email protected] unknown type is [B
"unknown"
}
}
}
}
...而不是進入的情況下「行(圖片:數組[字節])」作爲希望的那樣,它進入「行(一些(未知:任何))「情況。我的println輸出「[B @ 11be1c6未知類型爲[B」
我不知道B是什麼類型[或者我可能出了問題......
謝謝你,弘。我選擇了第一個選項來匹配「Row(Some(image:Array [Byte]))」。我感到有點傻,犯這樣一個明顯的錯誤。再次感謝。 –