1

I want to make file download from a database using Play framework. But when I use this code I get this message:

value as is not a member of Array[Byte]

And if I change Ok(bytOfImage.as("image/jpg")) to Ok(bytOfImage) it works good but I get a file with a name: secondindex without .jpg

Here's my controller:

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"))
    }
Daniel Olszewski
  • 13,995
  • 6
  • 58
  • 65
van van
  • 13
  • 1
  • 4

2 Answers2

0

You are calling the as method on the wrong object. It should look as follows:

Ok(bytOfImage).as("image/jpg")
Daniel Olszewski
  • 13,995
  • 6
  • 58
  • 65
  • Thank you! It's work! Could you say me please how I can download my image, because now it's showing in browser - but I wanna download. – van van Jun 23 '15 at 12:42
  • You need to set the `Content-Disposition` header to `attachment`. In accordance with this http://stackoverflow.com/questions/11559304/how-to-send-a-file-to-browser-for-downloading answer, you can pass InputStream to the `Ok()` method to set it automatically. Converting your byte array into a stream shouldn't be a problem. – Daniel Olszewski Jun 23 '15 at 12:55
0

If you need download images from browser, you can use method SimpleResult and add in header"Content-Disposition" -> "attachment"

For example change row Ok(bytOfImage.as("image/jpg")) in you code on

val enumImg: Enumerator[Array[Byte]] = { Enumerator(bytOfImage) }
SimpleResult (
 header = ResponseHeader(200, Map("Content-Disposition" -> "attachment")),
 body = enumImg
 )