gin framework Model + upload files in Go language (8)

In Gin framework, we usually use MVC pattern to organize our applications. MVC stands for Model-View-Controller, which divides our application into three different layers, each with its specific responsibilities.

Among them, the Controller is responsible for processing user requests, presenting views, and calling the Model to process business logic and data. View is responsible for displaying data and user interface.

In this case we can separate the controller from the model code. This can be done by creating a separate directory, such as "controllers", and writing and handling all controller code there.

When calling the model in the controller, we can handle all the business logic and data processing by importing the model and calling its methods. At the same time, we can also use the template rendering function of the Gin framework to render the data returned by the model into the HTML view. This achieves the goal of completely separating the model's data and business logic from the HTML view.

 Use in the main.go main entrance:

Render to html page, view layer

The above is a single file. How to enter the routing group from the request routers —> controllers —> template(view). This flow sequence is mixed with tools tool functions. Specifically

You can view the uploaded leaflet file:

How can we upload multiple files?

To implement file upload in the Gin framework, you need to use the Multipart/Form data type. Requests for this data type are split into two parts: text fields and file data. In addition, the Gin framework has a built-in multipart.Form parser c.MultipartForm(), which facilitates us to process uploaded files. Here are the specific steps:

1. In HTML, set the enctype attribute of the form to multipart/form-data, so that the server will know that this is a request to upload a file.

Note: c.Request.MultipartForm Is a field used to access multi-part form data in the original request object. This field gives you an  *multipart.Form object whose methods you can use to parse and process multipart form data.

2. On the server side, obtain the file data in the request. Use c.Request.MultipartForm() to obtain the multipart.Form data type. This method automatically parses the text fields and file data in the request. File data is saved in the server's memory or disk. You can use the c.SaveUploadedFile() method to save the file to the specified path.

3. If you want to obtain the metadata of the uploaded file, such as the file name, you can use c.Request.MultipartForm.File[filename], where filename refers to the form field name of the uploaded file. This method returns a pointer of type multipart.FileHeader, from which we can obtain the metadata of the file. For example, if we want to get the file name, we can use c.Request.MultipartForm.File[filename][0].Filename.

4. For uploading multiple files, we need to use a loop to process the data of each uploaded file. Here is the sample code:

func main() {
    router := gin.Default()

    router.POST("/upload", func(c *gin.Context) {
        //设置最大内存
        c.Request.ParseMultipartForm(32 << 20)

        //获取multipart/form-data数据类型
        form := c.Request.MultipartForm

        //获取上传的文件
        files := form.File["upload[]"] 

        //循环处理每个上传文件
        for _, file := range files {
            //保存文件到指定的路径
            err := c.SaveUploadedFile(file, "uploads/"+file.Filename)
            if err != nil {
                log.Println(err)
            }
        }

        c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))
    })

    router.Run(":8080")
}

This code handles the form field named "upload[]". For each uploaded file, it will save the file to the uploads directory and return the number of uploaded files.

In addition, there is a method [c.MultipartForm()]: c.MultipartForm() it is a method used to parse and bind the multi-part form data in the original request object to the Gin context object. This method returns an  (*multipart.Form, error) object.

Example:

func uploadMultiFiles(c *gin.Context) {
	// 获取上传的多个文件
	form, _ := c.MultipartForm()
	files := form.File["file"]

	// 遍历保存多个文件
	for _, file := range files {
		filename := file.Filename
		dst := "./upload/" + filename
		// 创建目录
		err := os.MkdirAll(path.Dir(dst), os.ModePerm)
		if err != nil {
			c.String(http.StatusBadRequest, "CreateDir failed: "+err.Error())
			return
		}
		// 保存文件
		if err := c.SaveUploadedFile(file, dst); err != nil {
			c.String(http.StatusBadRequest, "Upload failed: "+err.Error())
			return
		}
	}
	c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))
}

In the above example, we can obtain the uploaded form through the c.MultipartForm() method, and obtain multiple uploaded files using form.File["file"] . Then iterate through these files, create a directory with the same name and save the files. Finally, the response message is written into the response body.

The difference between two types of multiple file uploads at the same time:

c.Request.MultipartForm and  c.MultipartForm() are two methods in the Gin framework for handling multi-part form data. They are functionally similar but use slightly different ways.

  1. c.Request.MultipartForm:

    • This is a structure field used to access  http.Request multi-part form data in the underlying object.
    • It does not require function calls, and  c.Request.MultipartForm you can access the parsed form data directly.
    • When using this method, you need to first call the method in the function that handles routing  c.Request.ParseMultipartForm for resolution.
  2. c.MultipartForm():

    • This is a function that returns the parsed multipart form data from the request.
    • It requires a function call  c.MultipartForm() to get the form data.
    • When using this method, the Gin framework automatically parses the multipart form data without the need for an explicit call  c.Request.ParseMultipartForm.

Which method to use depends on your personal preference and specific needs:

  • http.Request Use this  if you prefer to directly manipulate the underlying  object and access multi-part form data within it c.Request.MultipartForm.
  • If you want to get parsed multi-part form data with a simple function call, you can use  c.MultipartForm().

gin.Default() No matter which method you choose, you will need to add middleware, such as or  , in the function that handles routing  gin.RouterGroup.Use()to ensure that the Gin framework correctly parses and processes multi-part form data.

Supplement an example of a relatively intuitive multi-file upload, suitable for a small number of multiple files;

index.html page View (view layer)

    <form action="/upfile/add" method="post" enctype="multipart/form-data">
        用户名:<input type="text" name="username" id="username">
        <br>
        头像1: <input type="file" name="file1" id="file1">
        <br>
        头像2: <input type="file" name="file2" id="file2">

        <br>
        <input type="submit" value="提交">
    </form>

controllers

func (con UpfileControllers) Add(c *gin.Context) {
	username := c.PostForm("username")
	// 1.form表单上传file 文件如何接收?
	file1, err1 := c.FormFile("file1")
	file2, err2 := c.FormFile("file2")
	//err == nil 表示“没有发生错误” 就上传文件到本地  ./static/upload/ 拼接上文件名字
	if err1 == nil {
		dst1 := path.Join("./static/upload", file1.Filename)

		c.SaveUploadedFile(file1, dst1)
		fmt.Println("file文件------")
	}
	if err2 == nil {
		dst2 := path.Join("./static/upload", file2.Filename)

		c.SaveUploadedFile(file2, dst2)
		fmt.Println("file文件------")
	}

	c.String(200, "上传文件--string-success-用户%v-图片%v \n", username, file1.Filename, file2.Filename)

}


// 终端输出

上传文件--string-success-用户eee-图片红点奖.png| 图片logo.png  



routers (routes) upfileRouter.go

package routers

import (
	"***/controllers/upfile"
	"***/middlewares"

	"github.com/gin-gonic/gin"
)

func UpfileRouterInit(r *gin.Engine) {
	upfileRouter := r.Group("/upfile", middlewares.InitMiddleWares) //添加一个中间件测试一下
	{
		upfileRouter.GET("/", upfile.UpfileControllers{}.Index)
		upfileRouter.POST("/add", upfile.UpfileControllers{}.Add)
	}
}

The above is another embodiment of the use of multiple files.

Hope it will be helpful to your study! Let’s encourage each other…

Guess you like

Origin blog.csdn.net/A_LWIEUI_Learn/article/details/131422637