一、引入 gin 框架import "ginhub.com/gin-gonic/gin
二、渲染页面router := gin.Default()
router.LoadHTMLGlob("view/*")
router.GET("/upload",func(c *gin.Context) {
c.HTML(http.StatusOK,"upload.tmpl",gin.H{})
})
三、处理上传文件router.POST("/upload", func(c *gin.Context) {
// Source
file, err := c.FormFile("file")
if err != nil {
c.String(http.StatusBadRequest, fmt.Sprintf("get form err: %s", err.Error()))
return
}
basePath := "./upload/"
filename := basePath + filepath.Base(file.Filename)
if err := c.SaveUploadedFile(file, filename); err != nil {
c.String(http.StatusBadRequest, fmt.Sprintf("upload file err: %s", err.Error()))
return
}
c.String(http.StatusOK,fmt.Sprintf("文件 %s 上传成功 ", file.Filename))
})
全部代码:package main
import (
"github.com/gin-gonic/gin"
"net/http"
"fmt"
"path/filepath"
)
func main() {
router := gin.Default()
router.LoadHTMLGlob("view/*")
router.GET("/upload",func(c *gin.Context) {
c.HTML(http.StatusOK,"upload.tmpl",gin.H{})
})
router.MaxMultipartMemory = 8 << 20 // 8 MiB
router.POST("/upload", func(c *gin.Context) {
file, err := c.FormFile("file")
if err != nil {
c.String(http.StatusBadRequest, fmt.Sprintf("get form err: %s", err.Error()))
return
}
basePath := "./upload/"
filename := basePath + filepath.Base(file.Filename)
if err := c.SaveUploadedFile(file, filename); err != nil {
c.String(http.StatusBadRequest, fmt.Sprintf("upload file err: %s", err.Error()))
return
}
c.String(http.StatusOK,fmt.Sprintf("文件 %s 上传成功 ", file.Filename))
})
router.Run(":8080")
}