3

Uploading a file is a process in which a user uploads a file from the client to the server. Here is a simple example of uploading a file:
First write a front-end page:

 <!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>

The result is as follows:

  • Remember to add this attribute to the html form tag: enctype="multipart/form-data" for binary file transfer.

Then write this in 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")
}

The result uploads the file successfully:

📢

  • The default memory limit for submitting files using multipart forms is 32Mb, which can be accessed via router.MaxMultipartMemory属性进行修改
  • Multiple file upload reference: Blog

Reference: bilibili

LiberHome
409 声望1.1k 粉丝

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