Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails download file

I'v used this method to copy a file to a folder in my project(first method), and I have edited it so the location is stored on my 'Location' in class Submissions (see below).

Now I want to be able to, after clicking on an image in my view, download that file. How can I do that ?

class Submissions {

    Date dateSub
    String Location
    String fileName

}
like image 306
Michael Avatar asked May 24 '11 11:05

Michael


1 Answers

I have done something similar to following:

Assuming your download page has the relevant Submissions instance...

<g:link action="downloadFile" id="${aSubmission.id}">
    <img>...etc...</img>
</g:link>

Then in controller (is your "location" the path to the file?):

def downloadFile = {
    def sub = Submissions.get(params.id)
    def file = new File("${sub.location}/${sub.fileName")
    if (file.exists())
    {
        response.setContentType("application/octet-stream") // or or image/JPEG or text/xml or whatever type the file is
        response.setHeader("Content-disposition", "attachment;filename=\"${file.name}\"")
        response.outputStream << file.bytes
    }
    else render "Error!" // appropriate error handling
}
like image 165
Chris Avatar answered Nov 01 '22 03:11

Chris