一、引入 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")
}
文档链接:https://github.com/gin-gonic/...
有疑问加站长微信联系(非本文作者)