Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 389
Alex03 Avatar asked Jul 15 '26 11:07

Alex03


1 Answers

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.

like image 128
Pasukaru Avatar answered Jul 24 '26 04:07

Pasukaru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!