Play-mini: how to return an image

2.1k views Asked by At

I'm trying to serve an image from a play-mini application.

object App extends Application {
  def route = {
    case GET(Path("/image")) => Action { request =>
      Ok( Source.fromInputStream(getClass.getResourceAsStream("image.gif")).toArray ).as("image/gif")
    }
  }
}

Unfortunately, this does noe work :) I get the following error

 Cannot write an instance of Array[Char] to HTTP response. Try to define a Writeable[Array[Char]]
2

There are 2 answers

1
4e6 On BEST ANSWER

Don't know about play-mini, but in play20 there is predefined Writeable[Array[Byte]], so you need to provide Array[Byte] for file handling. Also, there is a bit of documentation about serving files in play20.

0
John Spax On

I had the same problem and kept scratching my head for almost a week. Turned out the solution that worked for me was the following piece of code in my controller class:

    def getPhoto(name: String)  = Action {
    val strPath = Paths.get(".").toAbsolutePath.toString() + "/public/photos/" + name
    val file1: File = strPath
      .toFile
    val fileContent: Enumerator[Array[Byte]] = Enumerator.fromFile(new java.io.File(file1.path.toString))
    Ok.stream(fileContent).as("image/jpeg")
  }

And the route was defined as below:

GET         /photos/:name                                                 controllers.myController.getPhoto(name)

Hence typing the URL with the photos extension displayed the photo on the browser like so: http://localhost:9000/photos/2018_11_26_131035.jpg

The image is saved in a folder "public/photos" in the root folder of the application and not necessarily the assets folder. Hope this helps someone :-)