在Grails 4.2.2中将CSV下载到浏览器

时间:2014-10-14 14:48:05

标签: csv grails

我一直尝试将一个CSV文件以grails格式下载到浏览器中,但未成功。我有数据以字节为单位,我使用以下代码没有运气...我已经尝试了几个选项,如渲染,但似乎没有什么对我有用。有什么建议吗?

response.contentType='text/csv';
            response.setHeader("Content-Transfer-Encoding", "binary");
            response.setHeader("Cache-Control", "no-cache, must-revalidate");
            response.setHeader("Pragma", "no-cache");
            response.setCharacterEncoding("UTF-8")
            response.outputStream << data.bytes
            response.outputStream.flush();

旁注:我已成功通过电子邮件发送字节,并将其作为CSV文件正确打开

1 个答案:

答案 0 :(得分:0)

尝试将byte []包装为流:

response.outputStream << new ByteArrayInputStream(data.bytes)

一个对我有用的更完整的例子:

        try {
            ByteArrayInputStream inStream = new ByteArrayInputStream(data.bytes)
            response.setContentType("text/csv")
            //response.contentLength = data.bytes.length // optional, I think lets browser show progress?
            response.setHeader("Content-disposition", "attachment;filename=data.csv")
            // response.setHeader("Cache-Control", "no-transform") // Disable compression on the output          
            response.outputStream << inStream
        }
        finally {
            inStream.close()
        }