Play Framework: Handling dynamic created files (images) in PRODUCTION mode

一个人想着一个人 提交于 2019-12-06 11:59:09

Here's how I fix this

ISSUE 1

For upload file path, in play you can define configurations in conf/application.conf file, and you can use different file for production mode, using -Dconfig.file=/path/to/the/file.

So I defined an attribuite called myapp.image.base, in debug mode just set it to "", and in production mode (I created a file called conf/application.prod.conf) , I put an absolute path to it. So in my code, I always use the following command for file path (it's in Java, but you should find a similar way in Scala for reading configuration)

Play.application().configuration().getString("myapp.image.base")+"img" 

ISSUE 2

For serving image You need to create a router. 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 from url /user/images/

Play reads files off the classpath (which includes the assets directory). On the JVM, the classpath is immutable—once started, files added to folders on the classpath will not actually be added to the classpath.

This works in development mode because Play reloads the classpath whenever it detects a change. That same hot-reloading is not enabled in production (for good reason).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!