2013-01-06 59 views
5

我想我正確地將圖像保存到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是什麼類型[或者我可能出了問題......

回答

5

它字節的Java中的數組(字節[])。 >「我不知道什麼類型[B」。

而且你也可以在這種情況下寫match { case Row(Some(image: Array[Byte])) => },這可能會更好。

或者你也許可以這樣做,如下所示。

val results: Stream[Array[Byte]] = SQL(cmd stripMargin) 
    .on("badgeHandle" -> "name")().map { row => row[Array[Byte]]("img") } 

...糟糕,得到了以下編譯錯誤。

<console>:43: error: could not find implicit value for parameter c: anorm.Column[Array[Byte]] 
      val res: Stream[Array[Byte]] = SQL(cmd stripMargin).on("badgeHandle" -> "name")().map { row => row[Array[Byte]]("img") } 

不幸的是,默認情況下不支持scala.Array。如果你模仿其他類型的方式,它的工作原理。

implicit def rowToByteArray: Column[Array[Byte]] = { 
    Column.nonNull[Array[Byte]] { (value, meta) => 
    val MetaDataItem(qualified, nullable, clazz) = meta 
    value match { 
     case bytes: Array[Byte] => Right(bytes) 
     case _ => Left(TypeDoesNotMatch("...")) 
    } 
    } 
} 
val results: Stream[Array[Byte]] = SQL(cmd stripMargin) 
    .on("badgeHandle" -> "name")().map { row => row[Array[Byte]]("img") } 

https://github.com/playframework/Play20/blob/master/framework/src/anorm/src/main/scala/anorm/Anorm.scala

+0

謝謝你,弘。我選擇了第一個選項來匹配「Row(Some(image:Array [Byte]))」。我感到有點傻,犯這樣一個明顯的錯誤。再次感謝。 –

相關問題