package main import ( "fmt" "io" "net/http" "os" "path/filepath" "strings" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.POST("/upload", func(c *gin.Context) { file, header, err := c.Request.FormFile("file") if err != nil { c.String(http.StatusBadRequest, fmt.Sprintf("文件上传失败: %s", err.Error())) return } defer file.Close() // 指定保存目录 uploadDir := filepath.Join("./uploads", strings.Split(header.Filename, ".")[0]) err = os.MkdirAll(uploadDir, os.ModePerm) if err != nil { c.String(http.StatusInternalServerError, fmt.Sprintf("创建上传目录失败: %s", err.Error())) return } // 指定保存文件路径 filePath := filepath.Join(uploadDir, header.Filename) out, err := os.Create(filePath) if err != nil { c.String(http.StatusInternalServerError, fmt.Sprintf("保存文件失败: %s", err.Error())) return } defer out.Close() _, err = io.Copy(out, file) if err != nil { c.String(http.StatusInternalServerError, fmt.Sprintf("保存文件失败: %s", err.Error())) return } c.String(http.StatusOK, fmt.Sprintf("文件 %s 上传成功", header.Filename)) }) router.Run(":8080") }