Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force grails to download csv files?

In my gsp view, I have this code :

<g:each in="${fileResourceInstanceList}" status="i" var="fileResourceInstance">

<tr class="${(i % 2) == 0 ? 'odd' : 'even'}">
<td>${fileResourceInstance.decodeURL()}</td>

<td><a href="${createLinkTo( dir:"/upload_data/datasets/ds"+signalDataInstance.datasetID , file: fileResourceInstance.decodeURL(), absolute:true )}" target="_new">view</a></td>

<td><g:link action="deleteFile" id="${fileResourceInstance.replace('.','###')}" params="[rs:signalDataInstance.datasetID]" onclick="return confirm('Are you sure?');"> delete </g:link></td>
</tr>
</g:each>

I would like to download my csv files, and not read my csv files in my browser !
How to force download ?

Here code part in my controller :

    def f = new File( "${linkDir}".toString() )
    if( f.exists() ){
        f.eachFile(){ file->
        if( !file.isDirectory() )
            fileResourceInstanceList.add( file.name )
        }
    }

Where to add this part in my code to force download ? :

response.setHeader("Content-disposition", "attachment; filename=" + file.name + ".csv");
render(contentType: "text/csv", text: file.name.toString());
like image 365
Fabien Barbier Avatar asked Feb 19 '10 22:02

Fabien Barbier


People also ask

How do I download a CSV dataset?

Export data to a text file by saving itGo to File > Save As. The Save As dialog box appears. In the Save as type box, choose the text file format for the worksheet. For example, click Text (Tab delimited) or CSV (Comma delimited).

How do I download files from Grails?

How to Download different types of files using Grails 3. If you want to use server-side file download for different types of files like pdf, txt, docx etc then there are different ways to do it. def filePath = "/opt/tomcat/webapps/savedFile/filename. pdf" //I am saving files on tomcat.


1 Answers

The call to render is the problem - write directly to the response output stream:

response.setHeader "Content-disposition", "attachment; filename=${file.name}.csv"
response.contentType = 'text/csv'
response.outputStream << file.text
response.outputStream.flush()
like image 130
Burt Beckwith Avatar answered Sep 28 '22 06:09

Burt Beckwith