dongping1922 2015-06-24 05:06
浏览 615

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

  • 写回答

1条回答 默认 最新

  • doukang1962 2015-06-24 06:23
    关注

    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.

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog