beego输出到csv文件将数据转储到浏览器

beego输出到csv文件将数据转储到浏览器

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

问题描述

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

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

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

编写者:= csv.NewWriter(this.Controller.Ctx.ResponseWriter)
for _,记录:=范围记录{
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()

但是,它只显示浏览器中的记录数据,无法下载文件。我在这个下载文件控制器之前有一些登录控制器和过滤功能,我不知道它是否受到影响。我的代码有什么问题?谢谢 您应该始终设置响应标头第一,并且只有在开始将任何数据写入输出。我知道你在设置标题字段后调用了 writer.Flush(),但这并不能保证数据在之前不会被刷新或发送 - 这意味着默认标题为发送。在此之后,不能发送或更改其他头文件。



CSV的正确MIME类型是 text / csv 不是 application / csv ()。

此外,标题更像浏览器的提案。这是你建议的一个反应是要保存的文件,但是从服务器端你不能强制浏览器真正保存对文件的响应并且不显示它。



请参阅,和 rfc6266 获取有关Content-Disposition标题字段的更多详细信息。基本上,它传达了演示信息。


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

解决方案

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.

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.

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

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

08-19 14:43