grails,如何强制浏览器下载文件

编程入门 行业动态 更新时间:2024-10-26 18:29:07
本文介绍了grails,如何强制浏览器下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在控制器中,我这样做是为了尝试让浏览器在用户单击链接时下载文件:

In the controller, I do this to try to get the browser to download a file when the user clicks on a link:

render( contentType: 'text/csv', text: output);

此功能在Chrome浏览器中有效,但在IE或safari中不起作用,它们只是显示数据。而且,它以数字显示文件名(碰巧是网址上的ID,例如www.me/show/1

This works in Chrome, but does not work in IE or safari, they just show the data. Also, it shows the file name as a number (which happened to be the Id on the url, such as www.me/show/1

显然。修复下载的方法是将其转换为八位位组流,这可以在htaccess文件中完成,但是我不使用apache。有没有办法做到这一点呢?我想这是一个常见的情况。

Apparently. the way to fix the download is to convert to an octet stream. This can be done in a htaccess file, but Im not using apache. Is there any way to do this in grails? I would imagine its a common scenario.

在php中,可以这样做:

In php, one might do this:

header('Content-Disposition: attachment; filename="downloaded.csv"');

有什么想法吗?

在阅读下面的两个回复后(也许谢谢!),此方法有效:

After reading the two repsonses below (may thanks!) this worked:

response.setHeader "Content-disposition", "attachment; filename=report.csv" response.contentType = 'text/csv' response.outputStream << output response.outputStream.flush()

令人惊讶的是,我可以拿一个字符串并用<<来写输出流。我正试图

The amazing thing is that I could take a string and use << to write it to the output stream. I was going to try to work out how to turn the string it something like a stream.

推荐答案

class DownloadController { def download(long id) { Document documentInstance = Document.get(id) if ( documentInstance == null) { flash.message = "Document not found." redirect (action:'list') } else { response.setContentType("APPLICATION/OCTET-STREAM") response.setHeader("Content-Disposition", "Attachment;Filename=\"${documentInstance.filename}\"") def outputStream = response.getOutputStream() outputStream << documentInstance.filedata outputStream.flush() outputStream.close() } } }

请参阅此网站更多

更多推荐

grails,如何强制浏览器下载文件

本文发布于:2023-11-01 20:39:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1550358.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:浏览器   文件   grails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!