Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serving local images with Play 2 / Scala

I'm trying to figure out a pattern for uploading and serving files (images) locally. I figured out the upload part, but a little confused on the storage and serve part.

I'm confused about how to display locally stored images on a single page using "Ok.sendFile". How do tie it into "img src" tags on the view? The other option I could think of is to run a (separate) web server locally just for storing files, which doesn't make much sense.

like image 332
Turar Avatar asked Jan 12 '23 16:01

Turar


1 Answers

Just add an Action in a Controller that provides the image:

def picture(name: String) = Action {

   Ok.sendFile(new java.io.File(name)) // the name should contains the image extensions
}

Then add the corresponding route in your routes file:

GET /picture/:name  controllers.MyPictureController.picture(name: String)

And your HTML should look like:

<img src="/picture/image.png">

or if you use the Scala templates:

<img src="@routes.controllers.MyPictureController.picture("image.png")">
like image 118
ndeverge Avatar answered Jan 21 '23 15:01

ndeverge