Skip to content

Gin 框架的文件上传和下载

Published: at 02:56 AMSuggest Changes

Gin 的上传

直接看官方示例就可以 - https://gin-gonic.com/docs/examples/upload-file/multiple-file/

func main() {
	router := gin.Default()
	// Set a lower memory limit for multipart forms (default is 32 MiB)
	router.MaxMultipartMemory = 8 << 20  // 8 MiB
	router.POST("/upload", func(c *gin.Context) {
		// Multipart form
		form, _ := c.MultipartForm()
		files := form.File["upload[]"]

		for _, file := range files {
			log.Println(file.Filename)

			// Upload the file to specific dst.
			c.SaveUploadedFile(file, dst)
		}
		c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))
	})
	router.Run(":8080")
}

Gin 的 下载

一个是静态文件服务 - https://gin-gonic.com/zh-cn/docs/examples/serving-static-files/ 另一个是 Github Readme.md - https://github.com/gin-gonic/gin#serving-data-from-file

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

	router.GET("/local/file", func(c *gin.Context) {
		c.File("local/file.go")
	})

	var fs http.FileSystem = // ...
	router.GET("/fs/file", func(c *gin.Context) {
		c.FileFromFS("fs/file.go", fs)
	})
}

Previous Post
Swift 文字识别教程与资源整理
Next Post
Linux 性能监控:查看进程内存和 CPU 占用