reectrix
reectrix

Reputation: 8629

Open or download URL link in Grails Controller

I want to render or download a URL that links to a PDF in a Grails controller method. I'm okay with either opening this is in a new or the same tab, or just downloading it. How is this done in grails?

So far I have:

render(url: "http://test.com/my.pdf")

However, I get errors with this and other ways I've tried, such as rendering a response with content. Any clues?

Upvotes: 2

Views: 3041

Answers (2)

lvojnovic
lvojnovic

Reputation: 276

One option is

class ExampleController {
    def download() {
        redirect(url: "http://www.pdf995.com/samples/pdf.pdf")
    }
}

Going to localhost:8080/appName/example/download will, depending on the users browser preferences, either download the file or open the file in the same tab for reading.

I works with grails 2.5.0

Upvotes: 1

Shashank Agrawal
Shashank Agrawal

Reputation: 25807

Yes you can absolutely do it easily:

First get the file from the URL (if you don't have a local file) for example:

class FooService {

    File getFileFromURL(String url, String filename) {
        String tempPath = "./temp"     // make sure this directory exists

        File file = new File(tempPath + "/" + filename)
        FileOutputStream fos = new FileOutputStream(file)
        fos.write(new URL(url).getBytes())
        fos.close()
        file.deleteOnExit()

        return file
    }
}

Now in your controller, do this to allow user to automatically download your PDF file:

class FooController {

    def fooService

    def download() {
        String filename = "my.pdf"
        // You can skip this if you already have that file in the same server
        File file = fooService.getFileFromURL("http://test.com/my.pdf", filename)

        response.setContentType("application/octet-stream")
        response.setHeader("Content-disposition", "${params.contentDisposition}; filename=${filename}")
        response.outputStream << file.readBytes()
        return
    }
}

Now as the user will hit /foo/download the file will be dowloaded automatically.

Upvotes: 2

Related Questions