main.go 909 B

123456789101112131415161718192021222324252627282930313233343536
  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "path/filepath"
  6. "github.com/gin-gonic/gin"
  7. )
  8. func main() {
  9. router := gin.Default()
  10. // Set a lower memory limit for multipart forms (default is 32 MiB)
  11. router.MaxMultipartMemory = 8 << 20 // 8 MiB
  12. router.Static("/", "./public")
  13. router.POST("/upload", func(c *gin.Context) {
  14. name := c.PostForm("name")
  15. email := c.PostForm("email")
  16. // Source
  17. file, err := c.FormFile("file")
  18. if err != nil {
  19. c.String(http.StatusBadRequest, fmt.Sprintf("get form err: %s", err.Error()))
  20. return
  21. }
  22. filename := filepath.Base(file.Filename)
  23. if err := c.SaveUploadedFile(file, filename); err != nil {
  24. c.String(http.StatusBadRequest, fmt.Sprintf("upload file err: %s", err.Error()))
  25. return
  26. }
  27. c.String(http.StatusOK, fmt.Sprintf("File %s uploaded successfully with fields name=%s and email=%s.", file.Filename, name, email))
  28. })
  29. router.Run(":8080")
  30. }