golang gin下载文件

正常的后端 Gin 框架代码,使用 c.File() 文件来下载文件

package main

import (
	"github.com/gin-gonic/gin"
)

func main() {
    router := gin.Default()
 
    router.GET("/local/file", func(c *gin.Context) {
        c.File("local/file.go")
    })
    router.Run(":8080")
}

参考:Gin 实现上传/下载服务

如果碰到 wrote more than the declared Content-Length 问题

我的场景暂时还没有找到解决办法,可以参考下面这些方法,看看能否解决你的问题

1、指定 Content-Length 为 -1

c.Header("Content-Length", "-1")

或者

c.Header("Transfer-Encoding", "true")

参考:解决 golang 中 wrote more than the declared Content-Length

2、指定需要传输的文件类型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")

参考:golang+gin 实现文件下载GET接口api

3、用 ctx.DataFromReader 代替 C.File()

ctx.DataFromReader(200, response.ContentLength, "application/octet-stream", fileContent, nil) // fileContent是文件的字节流

参考:Go:如何通过GIN路由器将文件作为二进制流从AWS S3发送到浏览器?

4、用 c.Data 代替 c.File()

c.Data(200,"application/octet-stream",r) // r是文件的文件reader流指针

参考:请教问题: gin框架 返回二进制文件流时,响应该如何设置?

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值