Golang beego output to csv file dumps data to browser but does not dump files

I tried to output some data to csv file in gogang 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 displays the record data in the browser, it cannot download the file. I have a controller and filter function in front of this file upload controller, I have no influence on that. What's wrong with my code? Thanks to

+3


source to share


1 answer


You should always set response headers first and only then start writing any data to the output. I know what you called writer.Flush()

after setting the header fields, but this is not a guarantee that the data will not be cleared or sent before that, which would imply sending the headers by default. Thereafter, no additional headers can be sent or changed.

Also correct mime type for CSV text/csv

not application/csv

( rfc4180 ).

Also, headers are more like a "suggestion" for the browser. One thing you suggest to answer is the file to be saved, but from the server side, you cannot force the browser to actually save the response to the file and not display it.



See rfc1806 , rfc2183 and rfc6266 for more details on the header field "Content-Disposition"

. Basically it conveys information about the presentation.

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

+2


source







All Articles