英文:
Go how to response csv file?
问题
我正在创建一个Go服务器,并希望用CSV文件作为响应。我写了以下代码,但是它没有导致浏览器下载CSV文件。如何提示浏览器下载CSV文件?
import "github.com/gocarina/gocsv"
type Test struct {
ID int
Name string
Delete string
}
router.Get("/test", func(writer http.ResponseWriter, request *http.Request) {
writer.WriteHeader(http.StatusOK)
tests := []*Test{
{
ID: 1,
Name: "a",
Delete: "delete",
},
{
ID: 2,
Name: "b",
Delete: "delete",
},
}
writer.Header().Set("Content-Disposition", "attachment; filename=file.csv")
writer.Header().Set("Content-Type", "text/csv")
err := gocsv.MarshalFile(&tests, writer)
if err != nil {
logger.Error("MarshalFile", zap.Error(err))
}
})
你需要在响应头中设置Content-Disposition
和Content-Type
,以便浏览器能够正确地下载CSV文件。
英文:
I am creating a server in Go and I want to respond with a CSV file.
I wrote the following, this does not cause the browser to download the CSV file. How can I prompt the browser to download the CSV file?
import "github.com/gocarina/gocsv"
type Test struct {
ID int
Name string
Delete string
}
router.Get("/test", func(writer http.ResponseWriter, request *http.Request) {
writer.WriteHeader(http.StatusOK)
tests := []*Test{
{
ID: 1,
Name: "a",
Delete: "delete",
},
{
ID: 2,
Name: "b",
Delete: "delete",
},
}
w := multipart.NewWriter(writer)
ww, err := w.CreateFormFile("file.csv", "file.csv")
if err != nil {
logger.Error("CreateFormfile", zap.Error(err))
}
gocsv.Marshal(tests, ww)
})
答案1
得分: 6
如果你想告诉浏览器将响应呈现为可下载的文件,你可以使用Content-Disposition
头部:
rw.Header().Add("Content-Disposition", `attachment; filename="test.csv"`)
至于输出CSV文档本身,我不确定你试图通过响应多部分编码来实现什么目标,但你应该直接将CSV文件编组到原始的HTTP响应写入器中:
router.Get("/test", func(rw http.ResponseWriter, req *http.Request) {
tests := []*Test{
{
ID: 1,
Name: "a",
Delete: "delete",
},
{
ID: 2,
Name: "b",
Delete: "delete",
},
}
gocsv.Marshal(tests, rw)
})
英文:
If you want to tell the browser the to present the response as a file to download, you can use the Content-Disposition
header:
rw.Header().Add("Content-Disposition", `attachment; filename="test.csv"`)
As far as outputting the CSV document itself,
I'm not sure what you're trying to achieve by responding with a multipart encoding, but you should just marshal the CSV file directly into the original HTTP response writer:
router.Get("/test", func(rw http.ResponseWriter, req *http.Request) {
tests := []*Test{
{
ID: 1,
Name: "a",
Delete: "delete",
},
{
ID: 2,
Name: "b",
Delete: "delete",
},
}
gocsv.Marshal(tests, rw)
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论