Pular para o conteúdo

Download de arquivos

Echo fornece três helpers de contexto para retornar arquivos: c.File serve um arquivo usando a content disposition padrão do navegador, c.Inline sugere que o navegador exiba o arquivo no local, e c.Attachment solicita um download com um nome de arquivo informado.

package main
import (
"context"
"github.com/labstack/echo/v5"
"github.com/labstack/echo/v5/middleware"
)
func main() {
e := echo.New()
e.Use(middleware.RequestLogger())
e.Use(middleware.Recover())
e.GET("/", func(c *echo.Context) error {
return c.File("index.html")
})
e.GET("/file", func(c *echo.Context) error {
return c.File("echo.svg")
})
sc := echo.StartConfig{Address: ":1323"}
if err := sc.Start(context.Background(), e); err != nil {
e.Logger.Error("failed to start server", "error", err)
}
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>File download</title>
</head>
<body>
<p>
<a href="/file">File download</a>
</p>
</body>
</html>

Use c.Inline para enviar um header Content-Disposition: inline, de modo que o navegador renderize o arquivo no local em vez de baixá-lo.

package main
import (
"context"
"github.com/labstack/echo/v5"
"github.com/labstack/echo/v5/middleware"
)
func main() {
e := echo.New()
e.Use(middleware.RequestLogger())
e.Use(middleware.Recover())
e.GET("/", func(c *echo.Context) error {
return c.File("index.html")
})
e.GET("/inline", func(c *echo.Context) error {
return c.Inline("inline.txt", "inline.txt")
})
sc := echo.StartConfig{Address: ":1323"}
if err := sc.Start(context.Background(), e); err != nil {
e.Logger.Error("failed to start server", "error", err)
}
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>File download</title>
</head>
<body>
<p>
<a href="/inline">Inline file download</a>
</p>
</body>
</html>

Use c.Attachment para enviar um header Content-Disposition: attachment, solicitando que o navegador baixe o arquivo com o nome fornecido.

package main
import (
"context"
"github.com/labstack/echo/v5"
"github.com/labstack/echo/v5/middleware"
)
func main() {
e := echo.New()
e.Use(middleware.RequestLogger())
e.Use(middleware.Recover())
e.GET("/", func(c *echo.Context) error {
return c.File("index.html")
})
e.GET("/attachment", func(c *echo.Context) error {
return c.Attachment("attachment.txt", "attachment.txt")
})
sc := echo.StartConfig{Address: ":1323"}
if err := sc.Start(context.Background(), e); err != nil {
e.Logger.Error("failed to start server", "error", err)
}
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>File download</title>
</head>
<body>
<p>
<a href="/attachment">Attachment file download</a>
</p>
</body>
</html>