File Download

How to download a file?

Server

server.go

  1. package main
  2. import (
  3. "github.com/labstack/echo"
  4. "github.com/labstack/echo/middleware"
  5. )
  6. func main() {
  7. e := echo.New()
  8. e.Use(middleware.Logger())
  9. e.Use(middleware.Recover())
  10. e.GET("/", func(c echo.Context) error {
  11. return c.File("index.html")
  12. })
  13. e.GET("/file", func(c echo.Context) error {
  14. return c.File("echo.svg")
  15. })
  16. e.Logger.Fatal(e.Start(":1323"))
  17. }

Client

index.html

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>File download</title>
  6. </head>
  7. <body>
  8. <p>
  9. <a href="/file">File download</a>
  10. </p>
  11. </body>
  12. </html>

How to download a file as inline, opening it in the browser?

Server

server.go

  1. package main
  2. import (
  3. "github.com/labstack/echo"
  4. "github.com/labstack/echo/middleware"
  5. )
  6. func main() {
  7. e := echo.New()
  8. e.Use(middleware.Logger())
  9. e.Use(middleware.Recover())
  10. e.GET("/", func(c echo.Context) error {
  11. return c.File("index.html")
  12. })
  13. e.GET("/inline", func(c echo.Context) error {
  14. return c.Inline("inline.txt", "inline.txt")
  15. })
  16. e.Logger.Fatal(e.Start(":1323"))
  17. }

Client

index.html

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>File download</title>
  6. </head>
  7. <body>
  8. <p>
  9. <a href="/inline">Inline file download</a>
  10. </p>
  11. </body>
  12. </html>

How to download a file as attachment, prompting client to save the file?

Server

server.go

  1. package main
  2. import (
  3. "github.com/labstack/echo"
  4. "github.com/labstack/echo/middleware"
  5. )
  6. func main() {
  7. e := echo.New()
  8. e.Use(middleware.Logger())
  9. e.Use(middleware.Recover())
  10. e.GET("/", func(c echo.Context) error {
  11. return c.File("index.html")
  12. })
  13. e.GET("/attachment", func(c echo.Context) error {
  14. return c.Attachment("attachment.txt", "attachment.txt")
  15. })
  16. e.Logger.Fatal(e.Start(":1323"))
  17. }

Client

index.html

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>File download</title>
  6. </head>
  7. <body>
  8. <p>
  9. <a href="/attachment">Attachment file download</a>
  10. </p>
  11. </body>
  12. </html>