3

    上传文件是用户将文件从客户端上传到服务器的过程,下面举个简单的上传文件的例子:
    先写一个前端页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="f1">
    <input type="submit" value="上传">
</form>
</body>
</html>

结果如图:

  • 记得在html的form标签中加上这个属性:enctype="multipart/form-data" 用来二进制传文件。

然后再main.go中这样写:

package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
    "path"
)

func main() {
    r := gin.Default()
    r.LoadHTMLFiles("./index.html")
    r.GET("/index", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.html", nil)
    })
    r.POST("/upload", func(c *gin.Context) {
        //从请求中读取文件
        f, err := c.FormFile("f1")
        if err != nil {
            c.JSON(http.StatusBadRequest, gin.H{
                "error": err.Error(),
            })
        } else {
            //将文件保存在服务器
            //dst := fmt.Sprintf("./%s", f.Filename)//写法1
            dst := path.Join("./", f.Filename)
            c.SaveUploadedFile(f, dst)
            c.JSON(http.StatusOK, gin.H{
                "status": "ok",
            })
        }

    })
    r.Run(":9090")
}

结果上传文件成功:

📢

  • 使用multipart forms提交文件的默认内存限制是32Mb,可以通过router.MaxMultipartMemory属性进行修改
  • 多个文件上传参考:博客

参考:bilibili

LiberHome
409 声望1.1k 粉丝

有问题 欢迎发邮件 📩 liberhome@163.com