输出到csv文件会将数据转储到浏览器,但不会转储到文件 [英] Output to csv file dumps the data to browser but not dump to file

查看:148
本文介绍了输出到csv文件会将数据转储到浏览器,但不会转储到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在golang beego框架中将一些数据输出到csv文件中,这是我的代码

I tried to ouput some data to csv file in golang beego framework, here is my code

records := make([][]string,len(devicesData))

for k,v := range devicesData{
    records[k] = []string{v.Fields.Country,v.Fields.Imei[0],v.Fields.Number[0]}
}

writer := csv.NewWriter(this.Controller.Ctx.ResponseWriter)
for _, record := range records {
    err := writer.Write(record)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
}

this.Ctx.Output.Header("Content-Type", "application/csv")
this.Ctx.Output.Header("Content-Disposition", "attachment; filename=MyVerySpecial.csv")

    writer.Flush()

但是,它仅在浏览器中显示记录数据,无法下载文件。在此下载文件控制器之前,我具有一些日志记录控制器和过滤器功能,我不知道它是否受到影响。我的代码有什么问题?谢谢

However, it only shows the record data in browser, it cannot download the file. I have some loging controller and filter function before this download file controller, I do not whether it is affected. What's wrong with my code? Thanks

推荐答案

您应该始终先设置响应标头 ,然后再开始将任何数据写入输出。我知道您在设置标头字段后调用了 writer.Flush(),但这不能保证在此之前不会刷新或发送数据-这意味着默认标头被已发送。此后,将无法发送或更改其他标头。

You should always set response headers first and only after that start writing any data to the output. I know you called writer.Flush() after setting header fields, but that is no guarantee whatsoever that data will not be flushed or sent before that - which will imply default headers being sent. After this no additional headers can be sent or changed.

此外,CSV的正确MIME类型是 text / csv 而不是 application / csv rfc4180 )。

Also the proper mime type for CSV is text/csv not application/csv (rfc4180).

标头更像是浏览器的建议 。那是您建议响应是要保存的文件的一件事,但是从服务器端,您不能强制浏览器将响应真正保存为文件而不显示。

Also the headers are more like a "proposal" to the browser. That's one thing you suggest the response is a file to be saved, but from the server side you can't force the browser to really save the response to a file and not display it.

请参见 rfc1806 rfc2183 rfc6266 有关内容处置 标头字段的更多详细信息。

See rfc1806, rfc2183 and rfc6266 for more details about the "Content-Disposition" header field. Basically it communicates presentation information.


Content-Disposition响应标头字段用于传达
有关如何处理广告的附加信息。响应有效负载,以及
也可用于附加其他元数据,例如在本地保存响应有效负载时使用的文件名

The Content-Disposition response header field is used to convey additional information about how to process the response payload, and also can be used to attach additional metadata, such as the filename to use when saving the response payload locally.

这篇关于输出到csv文件会将数据转储到浏览器,但不会转储到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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