13

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());
Fabien Barbier
  • 1,514
  • 4
  • 28
  • 41

3 Answers3

25

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()
Burt Beckwith
  • 75,342
  • 5
  • 143
  • 156
0

You can also use the export plugin - it does what you want, and has some nice additional code that will follow associations, etc, as well as other output formats.

Might be a more maintainable solution depending on your requirements.

Jean Barmash
  • 4,788
  • 1
  • 32
  • 40
  • I'm parsing files from a folder, add files names in list "fileResourceInstanceList". In my view for each fileResourceInstanceList I add a link to csv files. Export plugin works with domain class, I'm not sure I can use this useful plugin ? – Fabien Barbier Feb 22 '10 at 16:49
  • hmm, probably not in that case, at least not without modifications. – Jean Barmash Feb 28 '10 at 20:44
0

Here is the fix :

In view (gsp) :

<td><g:link action="download" id="${fileResourceInstance}" params="[rs:signalDataInstance.datasetID]" > download </g:link></td>

In controller :

def download = {

def filename = params.id

def dsId = params.rs

def webRootDir = servletContext.getRealPath("/")

def linkDir = "${webRootDir}/upload_data/datasets/ds${dsId}"

    def file = new File( "${linkDir}".toString() + File.separatorChar + filename + ".csv" ) 

response.setHeader "Content-disposition", "attachment; filename=${file.name}"
      response.contentType = 'text/csv'
      response.outputStream << file.text
      response.outputStream.flush()

}

Fabien Barbier
  • 1,514
  • 4
  • 28
  • 41