main.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "github.com/gin-gonic/gin"
  10. )
  11. func main() {
  12. router := gin.Default()
  13. router.POST("/upload", func(c *gin.Context) {
  14. file, header, err := c.Request.FormFile("file")
  15. if err != nil {
  16. c.String(http.StatusBadRequest, fmt.Sprintf("文件上传失败: %s", err.Error()))
  17. return
  18. }
  19. defer file.Close()
  20. // 指定保存目录
  21. uploadDir := filepath.Join("./uploads", strings.Split(header.Filename, ".")[0])
  22. err = os.MkdirAll(uploadDir, os.ModePerm)
  23. if err != nil {
  24. c.String(http.StatusInternalServerError, fmt.Sprintf("创建上传目录失败: %s", err.Error()))
  25. return
  26. }
  27. // 指定保存文件路径
  28. filePath := filepath.Join(uploadDir, header.Filename)
  29. out, err := os.Create(filePath)
  30. if err != nil {
  31. c.String(http.StatusInternalServerError, fmt.Sprintf("保存文件失败: %s", err.Error()))
  32. return
  33. }
  34. defer out.Close()
  35. _, err = io.Copy(out, file)
  36. if err != nil {
  37. c.String(http.StatusInternalServerError, fmt.Sprintf("保存文件失败: %s", err.Error()))
  38. return
  39. }
  40. c.String(http.StatusOK, fmt.Sprintf("文件 %s 上传成功", header.Filename))
  41. })
  42. router.Run(":8080")
  43. }