官方文档:https://godoc.org/github.com/gin-gonic/gin
官方地址:https://github.com/gin-gonic/gin
测试工具:postman https://www.getpostman.com/downloads/

1.单文件上传

Gin框架入门(二)—文件上传
Gin框架入门(二)—文件上传
PS:

  1. 如果用html的表单上传文件,要添加 enctype=“multipart/form-data”,不然会上传失败。
  2. 如果用postman要在Body选择form-data。
func main() {
	router := gin.Default()
	router.POST("/upload", func(c *gin.Context) {
		//获取文件头
		file, err := c.FormFile("upload")
		if err != nil {
			c.String(http.StatusBadRequest, "请求失败")
			return
		}
		//获取文件名
		fileName := file.Filename
		fmt.Println("文件名:", fileName)
		//保存文件到服务器本地
		//SaveUploadedFile(文件头,保存路径)
		if err := c.SaveUploadedFile(file, fileName); err != nil {
			c.String(http.StatusBadRequest, "保存失败 Error:%s", err.Error())
			return
		}
		c.String(http.StatusOK, "上传文件成功")
	})
	router.Run()
}

效果展示:
Gin框架入门(二)—文件上传
Gin框架入门(二)—文件上传

2.多文件上传

func main() {
	router := gin.Default()
	router.POST("/upload", func(c *gin.Context) {
		//获取解析后表单
		form, _ := c.MultipartForm()
		//这里是多文件上传 在之前单文件upload上传的基础上加 [] 变成upload[] 类似文件数组的意思
		files := form.File["upload[]"]
		//循环存文件到服务器本地
		for _, file := range files {
			c.SaveUploadedFile(file, file.Filename)
		}
		c.String(http.StatusOK, fmt.Sprintf("%d 个文件被上传成功!", len(files)))
	})
	router.Run()
}

效果展示:
Gin框架入门(二)—文件上传
Gin框架入门(二)—文件上传

相关文章:

  • 2022-12-23
  • 2021-04-09
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-17
  • 2022-12-23
  • 2021-05-07
猜你喜欢
  • 2022-01-19
  • 2020-10-27
  • 2021-05-11
  • 2022-12-23
  • 2022-01-11
  • 2022-02-09
  • 2022-12-23
相关资源
相似解决方案