Gin Framework – Part 7

Introduction

File upload is already supported in the Gin framework, including single file upload and multi-file upload.

Single file upload

In the Gin framework, the FormFile("param") uploaded single file information can be received through the use of the following code:

  • Code example
//--- main.go ---------------
package main

import (
	"fmt"
	"go_use/practise"

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

func main() {
	// Create a default routing engine
	engine := gin.Default()
	// Register routing
	practise.TestRecFile(engine)
	_ = engine.Run(":9090")
}

//---file_receive.go-------
// Receive a single file
func TestRecFile(engine *gin.Engine) {
	// Set the memory limit to 8M, the default is 32MiB
	engine.MaxMultipartMemory = 8 << 20
	engine.POST("/file", func(context *gin.Context) {
		file, err := context.FormFile("img")
		if err != nil {
			context.JSON(500, gin.H{"err": err})
			return
		}
		// file rename
		dst := "./tmp/" + file.Filename
		fmt.Println(dst)
		// save image
		err = context.SaveUploadedFile(file, dst)
		if err != nil {
			context.JSON(500, gin.H{"err": "Failed to save file: " + err.Error()})
			return
		}
		context.JSON(200, gin.H{
			"msg":  "success",
			"name": file.Filename,
			"size": file.Size,
		})
	})
}
  • Request return
# Upload a single file
# File is stored in the tmp folder
$ curl -X GET http://127.0.0.1:9090/file
{"msg":"success","name":"steve.jpg","size":"79314"}

Multiple file upload

In the Gin framework, you can MultipartForm() receive multiple uploaded file information through the use of the following code:

//--- main.go ---------------
package main

import (
	"go_use/practise"

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

func main() {
	// create a default routing engine
	engine := gin.Default()
	// register routes
	practise.TestRecFiles(engine)
	_ = engine.Run(":9090")
}

//---file_receive.go-------
// Receive multiple files
func TestRecFiles(engine *gin.Engine) {
	// Set the memory limit to 8M, the default is 32MiB
	engine.MaxMultipartMemory = 8 << 20
	engine.POST("/files", func(context *gin.Context) {
		// Receive image
		form, _ := context.MultipartForm()
		files := form.File["imgList[]"]
		// Traverse save
		for _, file := range files {
			_ = context.SaveUploadedFile(file, "./tmp/"+file.Filename)
		}
		context.String(200, "Saved successfully!")
	})
}
  • Request return
# Upload multiple files
# Files stored in the tmp folder
$ curl -X GET http://127.0.0.1:9090/files
# Returns plain text: Saved successfully!