2015-07-26 14:58
浏览 46


I was wondering how to serve a file from a handler. I'm using go and gin and I've tried to do.

func DownloadHandler(c *gin.Context) {


func DownloadConfigs(c *gin.Context) {
   http.ServeFile(c.Writer, c.Request, "./downloads/")

and both of those solutions without the dot as well.

I'm open to any solution and because gin is compatible with the standard http lib, I can use non-gin specific solutions as well

图片转代码服务由CSDN问答提供 功能建议

我想知道如何从处理程序中提供文件。 我正在使用 gin ,我已经尝试过。

  func DownloadHandler(c * gin.Context){
 c.File(“ ./  downloads /“)

  func DownloadConfigs(c * gin.Context  ){
 http.ServeFile(c.Writer,c.Request,“ ./downloads/”)


我愿意接受任何解决方案,并且由于gin与标准的http lib兼容,因此我也可以使用非gin专用的解决方案

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanlin1931 2015-07-26 15:24

    Here is a complete working example using the standard http package. Please note, that the filename or path you use is relative to your current working directory.

    func main() {
        http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request)     {
            http.ServeFile(w, r, "file")
        err := http.ListenAndServe(":8080", nil)
        if err != nil {
            log.Fatal("ListenAndServe: ", err)
    打赏 评论
  • doukui9491 2016-12-26 08:11

    Just use this function from gin.Context:

    Something like this:

    const DOWNLOADS_PATH = "downloads/"
    ginRouter.GET("/download-user-file/:filename", func (ctx *gin.Context) {
        fileName := ctx.Param("filename")
        targetPath := filepath.Join(DOWNLOADS_PATH, fileName)
        //This ckeck is for example, I not sure is it can prevent all possible filename attacks - will be much better if real filename will not come from user side. I not even tryed this code
        if !strings.HasPrefix(filepath.Clean(targetPath), DOWNLOADS_PATH) {
            ctx.String(403, "Look like you attacking me")
        //Seems this headers needed for some browsers (for example without this headers Chrome will download files as txt)
        ctx.Header("Content-Description", "File Transfer")
        ctx.Header("Content-Transfer-Encoding", "binary")
        ctx.Header("Content-Disposition", "attachment; filename="+fileName )
        ctx.Header("Content-Type", "application/octet-stream")
    打赏 评论

相关推荐 更多相似问题