gin中的文件上传

1. 单文件上传

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
)

func main() {
	router := gin.Default()
	//为 multipart forms 设置较低的内存限制 (默认是 32 MiB)
	router.MaxMultipartMemory = 8 << 20
	router.POST("/upload", func(context *gin.Context) {
		// 单文件上传
		file, _ := context.FormFile("file")
		log.Println(file.Filename)
		// 上传文件到指定目录
		dst := fmt.Sprintf("./%s", file.Filename)
		context.SaveUploadedFile(file, dst)
		context.String(200, fmt.Sprintf("%s, uploaded!, Size: %d", file.Filename, file.Size))
	})
	router.Run()
}

  

2. 多文件上传

package main

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

func main() {
	router := gin.Default()
	//为 multipart forms 设置较低的内存限制 (默认是 32 MiB)
	router.MaxMultipartMemory = 8 << 20  // 8M
	router.POST("/upload", func(context *gin.Context) {
		// 多文件上传
		form, _ := context.MultipartForm()
		files := form.File["upload"]
		for _, file := range files {
			log.Println(file.Filename)
			// 保存文件
			dst := fmt.Sprintf("./%s", file.Filename)
			context.SaveUploadedFile(file, dst)
		}
		context.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))
	})
	router.Run()
}

  

posted @ 2021-10-20 16:30  专职  阅读(197)  评论(0编辑  收藏  举报