main.go
package main import ( "github.com/gin-gonic/gin" "net/http" "path" ) func main() { r :=gin.Default() r.LoadHTMLFiles("./upload.html") r.GET("/upload", func(c *gin.Context) { c.HTML(http.StatusOK,"upload.html",nil ) }) r.POST("/upload", func(c *gin.Context) { file,err :=c.FormFile("f1") if err != nil{ c.JSON(http.StatusInternalServerError,gin.H{ "message":err.Error(), }) } else { dst := path.Join("./"+file.Filename) c.SaveUploadedFile(file,dst) c.JSON(http.StatusOK,gin.H{ "message":"ok", "name":file.Filename, }) } //log.Printf(file.Filename) }) r.Run(":9999") /* 报错信息 { "message": "request Content-Type isn't multipart/form-data" } */ }
upload.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body>
{{/*
不要忘记 请求文件类型
*/}}
<form method="post" enctype="multipart/form-data"> {{/**/}} <input type="file" name="f1" > <input type="submit" value="提交"> </form> </body> </html>