见代码
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
server := gin.Default()
gin.SetMode(gin.DebugMode)
fmt.Println("Gin Running in", gin.Mode())
server.GET("/test", func(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{
"code": 1,
"msg": "success",
})
})
// uploadFile
saveUploadFile(server)
_ = server.Run(":8080")
}
func saveUploadFile(srv *gin.Engine) {
srv.MaxMultipartMemory = 8 << 20 // max = 8MB
srv.POST("/file", func(ctx *gin.Context) {
file, err := ctx.FormFile("file") // file as the form-data key
if err != nil {
ctx.JSON(500, gin.H{"err": err})
return
}
// file rename
dst := "./" + file.Filename
fmt.Println("save the uploadfile to dst:", dst)
// save image
err = ctx.SaveUploadedFile(file, dst)
if err != nil {
ctx.JSON(500, gin.H{"err": "file saving failed: " + err.Error()})
return
}
ctx.JSON(200, gin.H{
"msg": "success",
"name": file.Filename,
"size": file.Size,
})
})
}
postman测试: