使用 golang的gin框架實現,文件上傳

1、引入 gin 框架git

import "ginhub.com/gin-gonic/gin

2、渲染頁面github

router := gin.Default()
    router.LoadHTMLGlob("view/*")
    router.GET("/upload",func(c *gin.Context) {
        c.HTML(http.StatusOK,"upload.tmpl",gin.H{})
    })

3、處理上傳文件框架

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))
    })

所有代碼:code

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/...orm

相關文章
相關標籤/搜索