Gin返回文件形式
前言:似乎在官方文档只看见了怎么上传,并没有看到怎么下载...
文件流形式(发送下载链接)#
百度发现Gin早就有成熟的封装好的函数:
package gin
// File writes the specified file into the body stream in an efficient way.
func (c *Context) File(filepath string)
// FileAttachment writes the specified file into the body stream in an efficient way
// On the client side, the file will typically be downloaded with the given filename
func (c *Context) FileAttachment(filepath, filename string)
甚至封装的非常好...你只需要传入文件路径就会以文件流形式写在response里面了
出现wrote more than the declared Content-Length#
具体的解决办法我是参考这篇博客的:golang gin下载文件
采用这个办法,完美解决
指定需要传输的文件类型Content-Type 和 Content-Transfer-Encoding#
c.Header("Content-Type", "application/octet-stream")
c.Header("Content-Disposition", "attachment; filename="+fileName) // 用来指定下载下来的文件名
c.Header("Content-Transfer-Encoding", "binary")
后来我又出现了这个问题,经过一步步debug之后发现,是因为我在调用c.FileAttachment之后,又使用了自己封装好的将业务状态代码写入Response,导致最终的Content-Length大于c.FileAttachment设置的,从而导致panic
静态文件形式#
这个Gin的官网早有说明,分为三个方法:
func main() {
router := gin.Default()
router.Static("/assets", "./assets")
router.StaticFS("/more_static", http.Dir("my_file_system"))
router.StaticFile("/favicon.ico", "./resources/favicon.ico")
// 监听并在 0.0.0.0:8080 上启动服务
router.Run(":8080")
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人