Alex03
Alex03

Reputation: 131

Play Framework Get Asset Server Side

This seems like it should be extremely easy, but I can't figure it out. I need to get files from my /public folder on the server side of my application. I can get them using javascript or html with no problems. I'm using Java, play 2.2.1

I've tried messing around with this

Assets.at("/public", "images/someImage.png");

but I'm not sure how to turn that Action object into a File object.

Upvotes: 3

Views: 1084

Answers (2)

Pasukaru
Pasukaru

Reputation: 1105

The 'public' folder probably won't exist on the file system in a deployed environment (using $ activator stage), as the assets are packed into a .jar file located at target/universal/stage/lib/<PROJECT_NAME>-assets.jar.

So getting a java.io.File instance to that location is AFAIK not possible.

However, this is what I figured out to read a file's bytes (And convert them to a String - that's what I needed):

SomeController.java

private String getSomeFile() throws IOException {
    InputStream in = null;
    ByteArrayOutputStream out = null;

    try {
        in = Play.application().resourceAsStream("public/some/file.txt");
        out = new ByteArrayOutputStream();
        int len;
        byte[] buffer = new byte[1024 * 16];

        while ((len = in.read(buffer)) >= 0) {
            out.write(buffer, 0, len);
        }

        return new String(out.toByteArray(), "utf-8");
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) { /* ignore */ }
        }
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) { /* ignore */ }
        }
    }
}

Note: I used Play 2.3.7. I'm not sure if this will work on 2.2.1.

Hope this helps anyone.

Upvotes: 2

Ryan
Ryan

Reputation: 7247

Play.application().getFile will load a file relative to the current application path.

So:

Play.application().getFile("public/images/someImage.png");

Upvotes: -1

Related Questions