单文件上传示例:
main.go
router := router.InitRouter()
router.Run()
router/router.go
var router = gin.Default() func init() { //加载自定义函数 if v, ok := binding.Validator.Engine().(*validator.Validate); ok { v.RegisterValidation("capt", captcha.VerifyCaptcha) } //加载静态文件 router.Static("upload", "upload/") //加载view router.LoadHTMLGlob("view/*") } func InitRouter() *gin.Engine { router.GET("/index", user.Index) router.POST("/upload", upload.Upload) return router }
controller/user/index.go
func Index(c *gin.Context) { c.HTML(http.StatusOK, "upload.html", nil) }
common/upload/upload.go代码如下:
// 定义上传路径 const UPLOAD_DIR = "upload" func Upload(c *gin.Context) { file, err := c.FormFile("upfile") if err != nil { c.JSON(http.StatusForbidden, gin.H{ "code": 400, "error": err.Error(), }) return } arr := strings.Split(file.Filename, ".") filepath, ok := checkExtAndgetFilePath(arr[1]) if ok != true { c.JSON(http.StatusForbidden, gin.H{ "code": 400, "error": "invalid ext", }) return } if err = c.SaveUploadedFile(file, filepath); err != nil { c.JSON(http.StatusForbidden, gin.H{ "code": 400, "error": "upload failed", }) return } c.JSON(http.StatusOK, gin.H{ "code": 200, "error": "upload success", "img_url": filepath, }) return } // 检查扩展名,并返回文件路径 func checkExtAndgetFilePath(fileExt string) (string, bool) { allowExt := map[string]bool{ "jpg": true, "png": true, "jpeg": true, } if _, ok := allowExt[fileExt]; !ok { return "", false } //创建文件夹 if _, ok := os.Stat(UPLOAD_DIR); ok != nil { os.Mkdir(UPLOAD_DIR, os.ModePerm) } filePath := UPLOAD_DIR + "/" + strconv.FormatInt(time.Now().Unix(), 10) + "." + fileExt return filePath, true }
view/upload.html 模板文件
<body> <h3>单文件上传</h3> <form action="/upload" method="post" enctype="multipart/form-data"> <p><input type="file" name="upfile" id="upfile" /> <input type="submit" value="上传" /></p> </form> </body>
上传成功后返回:
多文件上传示例:
router/router.go
var router = gin.Default() func init() { //加载自定义函数 if v, ok := binding.Validator.Engine().(*validator.Validate); ok { v.RegisterValidation("capt", captcha.VerifyCaptcha) } //加载静态文件 router.Static("upload", "upload/") //加载view router.LoadHTMLGlob("view/*") } func InitRouter() *gin.Engine { router.GET("/index", user.Index) router.POST("/upload", upload.UploadMul) return router }
common/upload.go
// 定义上传路径 const UPLOAD_DIR = "upload" func UploadMul(c *gin.Context) { form, err := c.MultipartForm() if err != nil { c.JSON(http.StatusForbidden, gin.H{ "code": 400, "error": err.Error(), }) return } var urls []string files := form.File["upfile"] for _, file := range files { arr := strings.Split(file.Filename, ".") filepath, ok := checkExtAndgetFilePath(arr[1]) if ok != true { c.JSON(http.StatusForbidden, gin.H{ "code": 400, "error": "invalid ext", }) return } if err = c.SaveUploadedFile(file, filepath); err != nil { c.JSON(http.StatusForbidden, gin.H{ "code": 400, "error": "upload failed", }) return } urls = append(urls, filepath) } c.JSON(http.StatusOK, gin.H{ "code": 200, "error": "upload success", "img_url": urls, }) return } // 检查扩展名,并返回文件路径 func checkExtAndgetFilePath(fileExt string) (string, bool) { allowExt := map[string]bool{ "jpg": true, "png": true, "jpeg": true, } if _, ok := allowExt[fileExt]; !ok { return "", false } //创建文件夹 if _, ok := os.Stat(UPLOAD_DIR); ok != nil { os.Mkdir(UPLOAD_DIR, os.ModePerm) } filePath := UPLOAD_DIR + "/" + strconv.FormatInt(time.Now().UnixNano(), 10) + "." + fileExt return filePath, true }
view/upload.html
<body> <h3>单文件上传</h3> <form action="/upload" method="post" enctype="multipart/form-data"> <p><input type="file" name="upfile" multiple id="upfile" /> <input type="submit" value="上传" /></p> </form> </body>
其他文件跟单文件上传一致。
上传的时候按住ctrl,可选择多张图片,上传后效果:
上传后,需要静态文件显示的话,在路由中需要增加一行代码:
router.Static("upload", "upload/") //加载静态文件
不然,通过浏览器无法打开图片
完结
标签:文件,ok,upload,return,gin,go,router,上传 From: https://www.cnblogs.com/ypeih/p/17311747.html