2015-06-30 21:10:35 +02:00
|
|
|
## File Upload
|
|
|
|
|
|
|
|
- Multipart/form-data file upload
|
|
|
|
- Multiple form fields and files
|
|
|
|
|
|
|
|
Use `req.ParseMultipartForm(16 << 20)` for manually parsing multipart form. It gives
|
2015-07-02 06:22:51 +02:00
|
|
|
us an option to specify the maximum memory used while parsing the request body.
|
2015-06-30 20:51:08 +02:00
|
|
|
|
|
|
|
`server.go`
|
|
|
|
|
|
|
|
```go
|
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"os"
|
|
|
|
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/labstack/echo"
|
2015-07-02 20:14:09 +02:00
|
|
|
mw "github.com/labstack/echo/middleware"
|
2015-06-30 20:51:08 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
func upload(c *echo.Context) error {
|
|
|
|
req := c.Request()
|
|
|
|
|
|
|
|
// req.ParseMultipartForm(16 << 20) // Max memory 16 MiB
|
|
|
|
|
|
|
|
// Read form fields
|
|
|
|
name := req.FormValue("name")
|
|
|
|
email := req.FormValue("email")
|
|
|
|
|
|
|
|
// Read files
|
|
|
|
files := req.MultipartForm.File["files"]
|
2015-07-02 20:14:09 +02:00
|
|
|
for _, f := range files {
|
2015-06-30 20:51:08 +02:00
|
|
|
// Source file
|
|
|
|
src, err := f.Open()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer src.Close()
|
|
|
|
|
|
|
|
// Destination file
|
|
|
|
dst, err := os.Create(f.Filename)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer dst.Close()
|
|
|
|
|
|
|
|
if _, err = io.Copy(dst, src); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return c.String(http.StatusOK, "Thank You! %s <%s>, %d files uploaded successfully.",
|
|
|
|
name, email, len(files))
|
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
e := echo.New()
|
2015-07-02 20:14:09 +02:00
|
|
|
e.Use(mw.Logger())
|
|
|
|
e.Use(mw.Recover())
|
|
|
|
|
|
|
|
e.Static("/", "public")
|
2015-06-30 20:51:08 +02:00
|
|
|
e.Post("/upload", upload)
|
2015-07-02 20:14:09 +02:00
|
|
|
|
2015-06-30 20:51:08 +02:00
|
|
|
e.Run(":1323")
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
`index.html`
|
|
|
|
|
|
|
|
```html
|
|
|
|
<!doctype html>
|
|
|
|
<html lang="en">
|
|
|
|
<head>
|
|
|
|
<meta charset="utf-8">
|
2015-06-30 21:10:35 +02:00
|
|
|
<title>File Upload</title>
|
2015-06-30 20:51:08 +02:00
|
|
|
</head>
|
|
|
|
<body>
|
|
|
|
<h1>Upload Files</h1>
|
2015-06-30 21:10:35 +02:00
|
|
|
<form action="/upload" method="post" enctype="multipart/form-data">
|
2015-06-30 20:51:08 +02:00
|
|
|
Name: <input type="text" name="name"><br>
|
|
|
|
Email: <input type="email" name="email"><br>
|
|
|
|
Files: <input type="file" name="files" multiple><br><br>
|
|
|
|
<input type="submit" value="Submit">
|
|
|
|
</form>
|
|
|
|
</body>
|
|
|
|
</html>
|
|
|
|
|
|
|
|
```
|
|
|
|
|
2015-06-30 21:10:35 +02:00
|
|
|
## [Source Code](https://github.com/labstack/echo/blob/master/recipes/file-upload)
|