当前位置: > > > > 下载 golang 生成的文件时,文件下载适用于 Chrome,但不适用于 Firefox
来源:stackoverflow
2024-04-20 20:33:38
0浏览
收藏
从现在开始,努力学习吧!本文《下载 golang 生成的文件时,文件下载适用于 Chrome,但不适用于 Firefox》主要讲解了等等相关知识点,我会在中持续更新相关的系列文章,欢迎大家关注并积极留言建议。下面就先一起来看一下本篇正文内容吧,希望能帮到你!
问题内容
我有简单的 golang/gin-gonic rest 服务,可根据 /api/billing
的请求提供 excel 报告。当请求者将接受标头设置为 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
时,将提供 excel 文件,否则为 json。这段代码在 chrome 和 ie 中运行良好,但在 firefox 中运行不佳,我不知道为什么。
在 ff 调试器中,我看到实际内容传输到浏览器,但 ff 不向用户提供下载对话框。因此,对于用户来说,如果他点击链接,看起来就像没有发生任何事情。
我已经检查过弹出窗口没有被 ff 阻止,我还禁用了其他安全功能 https://support.mozilla.org/1/firefox/62.0.2/darwin/de/phishing-malware 以防万一。我还重新安装了普通 ff,没有任何扩展和任何更改。 windows 上的 ff 也会发生同样的情况。
r.get("/api/billing", func(c *gin.context) { if c.getheader("accept") == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" { b := api.getbillingreportexcel() extraheaders := map[string]string{ "content-disposition": "attachment;filename='billingreport.xlsx'", "content-transfer-encoding": "binary", "content-description": "excel billing report", } c.datafromreader(200, int64(b.len()),"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",&b,extraheaders) }else { billingtenants, _ := cache.get(c.request.requesturi) c.json(200, getbillingdata()) } })
这是请求标头,它们对于 ff 和 chrome 是相同的
http 请求:
host: localhost:8081 user-agent: mozilla/5.0 (macintosh; intel mac os x 10.13; rv:61.0) gecko/20100101 firefox/61.0 accept: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet accept-language: de,en-us;q=0.7,en;q=0.3 accept-encoding: gzip, deflate referer: http://localhost:8081/ connection: keep-alive
回应
HTTP/1.1 200 OK X-Powered-By: Express content-description: Excel Billing Report content-disposition: attachment; filename='BillingReport.xlsx' content-length: 11397 content-transfer-encoding: binary content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet date: Tue, 25 Sep 2018 12:17:41 GMT
解决方案
我花了几天时间尝试解决这个问题。然而我却在意想不到的地方发现了罪魁祸首。最后是前端应用程序的行为,因为我的印象是它只是一个被调用的链接,但我错了。
但是我想指出,我可以成功验证浏览器不关心 content-disposition
是否有 '
、"
或根本没有引用。
上面的 gin/golang 也能正常工作。
感谢大家帮助我。
您可能需要对 使用双引号 ("
),而不是单引号 ('
):
extraheaders := map[string]string{ "content-disposition": `attachment; filename="billingreport.xlsx"`, // note the double quotes -------------------^------------------^
参见 :
content-disposition = "Content-Disposition" ":" disposition-type *( ";" disposition-parm ) ... filename-parm = "filename" "=" quoted-string
还有:
定义了其他规则,但上面的简单引用是最简单的。
理论要掌握,实操不能落!以上关于《下载 golang 生成的文件时,文件下载适用于 Chrome,但不适用于 Firefox》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注公众号吧!