PlayFramework:值不是 Array[Byte] 的成员

PlayFramework: value as is not a member of Array[Byte]

我想使用 Play 框架从数据库下载文件。 但是当我使用这段代码时,我收到了这条消息:

value as is not a member of Array[Byte]

如果我将 Ok(bytOfImage.as("image/jpg")) 更改为 Ok(bytOfImage) 它工作正常但我得到一个名称为 secondindex 没有 .jpg

的文件

这是我的控制器:

def secondindex(number: Int) = Action {
    var bytOfImage =  Array[Byte](1)

    val conn = DB.getConnection()
    try {

      val stmt = conn.createStatement
      val rs = stmt.executeQuery("SELECT image from images where id = " + number)


       while(rs.next()) {
         var blob = rs.getBlob("image")

         bytOfImage = blob.getBytes(1, blob.length().toInt)
         blob.free()
       }

    } finally   {
      conn.close()   }
      Ok(bytOfImage.as("image/jpg"))
    }

您在错误的对象上调用了 as 方法。它应该如下所示:

Ok(bytOfImage).as("image/jpg")

如果需要从浏览器下载图片,可以使用方法SimpleResult 并添加 header"Content-Disposition" -> "attachment"

例如,在代码

中更改行 Ok(bytOfImage.as("image/jpg"))
val enumImg: Enumerator[Array[Byte]] = { Enumerator(bytOfImage) }
SimpleResult (
 header = ResponseHeader(200, Map("Content-Disposition" -> "attachment")),
 body = enumImg
 )