Search code examples
imagescalafileplayframeworkplayframework-2.3

How to view images from local directories in play scala project


I am newbie to Play scala framework,in my project I have a functionality of uploading a image and showing a uploaded image into view page.I have stored the uploaded images into my system's local folder and passed the images path into my view page,but it doesn't show the images. I have passed the image stored location path as imagepath and used the below code to view the image.

<img [email protected](imagepath) class="responsive" >

Note: If I stored the images in projectname/public/images project directory the images are showing in view page. please help me to resolve this issue.


Solution

  • You need to implement an action yourself. As I answered in Play Framework: Handling dynamic created files (images) in PRODUCTION mode

    Here's the steps First in your routes file, add something like this:

    GET /user/images/:name controllers.Application.imageAt(name:String)
    

    And write a simple file reader in action imageAt which return the file in stream. Again my sample is in Java but you should archive the same using Scala

        File imageFile = new File(ReportFileHelper.getImagePath());
        if (imageFile.exists()) {
        //resource type such as image+png, image+jpg
            String resourceType = "image+"+imageName.substring(imageName.length()-3);
            return ok(new FileInputStream(imageFile)).as(resourceType);
        } else {
            return notFound(imageFile.getAbsoluteFile());
        }
    

    After that, the images is reachable via revers router:

     <img [email protected](imageName)>
    

    Or directly via url

     <img src="/user/images/imageName">