grails,如何强制浏览器下载文件 [英] grails, how to force the browser to download a file

查看:101
本文介绍了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.com/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.com/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,如何强制浏览器下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆