如何强制grails下载csv文件?
在我的 gsp 视图中,我有以下代码:
<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>
我想下载我的 csv 文件,而不是在浏览器中读取我的 csv 文件!
如何强制下载?
这是我的控制器中的代码部分:
def f = new File( "${linkDir}".toString() )
if( f.exists() ){
f.eachFile(){ file->
if( !file.isDirectory() )
fileResourceInstanceList.add( file.name )
}
}
在我的代码中哪里添加此部分以强制下载? :
response.setHeader("Content-disposition", "attachment; filename=" + file.name + ".csv");
render(contentType: "text/csv", text: file.name.toString());
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());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对 render 的调用是问题所在 - 直接写入响应输出流:
The call to render is the problem - write directly to the response output stream:
您还可以使用 导出插件 - 它可以满足您的需求,并且有一些不错的附加代码它将遵循关联等以及其他输出格式。
根据您的要求,可能是一个更易于维护的解决方案。
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.
这是修复:
在视图(gsp)中:
在控制器中:
def download = {
}
Here is the fix :
In view (gsp) :
In controller :
def download = {
}