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

时间:2014-04-14 08:11:48

标签: grails download

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

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

这适用于Chrome,但在IE或Safari中不起作用,它们只显示数据。此外,它将文件名显示为数字(恰好是网址上的ID,例如www.me.com/show/1

显然。修复下载的方法是转换为八位字节流。这可以在htaccess文件中完成,但我不使用apache。有没有办法在grails中这样做?我认为这是一个常见的场景。

在php中,人们可能会这样做:

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

有什么想法吗?

在阅读下面的两个回复之后(可能会感谢!)这有效:

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

令人惊奇的是我可以拿一个字符串并使用&lt;&lt;将其写入输出流。我打算尝试解决如何将字符串转换为流的问题。

2 个答案:

答案 0 :(得分:4)

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()
        }
    }
}

refer this site for more

答案 1 :(得分:1)

您可以执行以下操作:http://lalitagarw.blogspot.com/2014/03/grails-forcing-file-download.html

class DownloadController {
    def downloadFile() {
    InputStream contentStream
    try {
    def file = new File("")  
    response.setHeader "Content-disposition", "attachment; filename=filename-with-extension"
    response.setHeader("Content-Length", "file-size")
    response.setContentType("file-mime-type")
    contentStream = file.newInputStream()
    response.outputStream << contentStream
    webRequest.renderView = false
    } finally {
    IOUtils.closeQuietly(contentStream)
  }
 }
}