gin学习笔记--文件上传

gin学习笔记--文件上传

相关资料:

gin中文文档

gin的标准库

gtihub地址

单文件上传

前端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
<body>
<form action="/upload" method="post"  enctype="multipart/form-data">
    <input type="file" name="f1">
    <input type="submit" value="上传">
</form>
</body>
</html>

后端;

package main

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

func main() {
	r := gin.Default()
	//处理multipart forms提交文件时默认的内存限制是32 MiB
	r.MaxMultipartMemory = 8    //router.MaxMultipartMemory = 8 << 20  // 8 MiB
	r.LoadHTMLFiles("./index.html")//解析模板
	r.GET("/index", func(c *gin.Context) {
		c.HTML(http.StatusOK,"index.html",nil)//渲染并发送
	})
	r.POST("/upload", func(c *gin.Context) {
		//从请求中读取文件
		f, err := c.FormFile("f1")  //根据name返回给第一个文件
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
		}else {
			//将读取到的文件保存到本地(服务端)
			//dst := fmt.Sprintf("./%s", f.Filename)
			dst := path.Join("./", f.Filename)//拼接字符串作为文件的路径
			_  = c.SaveUploadedFile(f,dst)//核心代码,将拿到的文件存储到指定位置
			c.JSON(http.StatusOK, gin.H{
				"status":"ok",
			})
		}
	})

	r.Run(":9090")
}

注:index.html和main.go在同一个文件夹下

逻辑分析:

  1. 首先定义好前端的模板
  2. 在后端进行模板解析
  3. 进行模板渲染
  4. 将模板发往浏览器
  5. 浏览器上传文件
  6. 后端拿到文件并保存

注意事项:

  1. form表中的enctype要设置成"multipart/form-data",这是post中用于传文件的格式。

  2. form表单中的action表示将表单数据发往何处,相当于做了跳转

    之前我一直不理解要怎样才能路由到c.Post()里的handler函数,原来是先访问路径.../index(GET方法),然后会上传后会跳到.../upload,这是便触发uploadHandle函数。

  3. form表单中<input type="file" name="f1">里的f1与c.FormFile("f1")里的f1是对应的。

多文件上传

前端:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
<body>
<form action="/upload" method="post"  enctype="multipart/form-data">
    <input type="file" name="f1">
    <input type="file" name="f1">
    <input type="submit" value="上传">
</form>
</body>
</html>

注意:这里加了一行同样的 <input type="file" name="f1">实现多个文件上传。他们都在同一个key下(name=f1)。

后端:

ackage main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"path"
)
func main() {
	r := gin.Default()
	//处理multipart forms提交文件时默认的内存限制是32 MiB
	r.MaxMultipartMemory = 8    //router.MaxMultipartMemory = 8 << 20  // 8 MiB
	r.LoadHTMLFiles("./index.html")
	r.GET("/index", func(c *gin.Context) {
		c.HTML(http.StatusOK,"index.html",nil)
	})
	r.POST("/upload", func(c *gin.Context) {
		form, _ := c.MultipartForm()
		files := form.File["f1"]//得到一个切片
		for _, file := range files {//遍历切片
			log.Print(file.Filename)
			dst := path.Join("./", file.Filename)//拼接存储路径
			//上传文件到指定的目录
			c.SaveUploadedFile(file, dst)
		}
		c.JSON(http.StatusOK, gin.H{
			"message" : fmt.Sprintf("%d files uploaded!", len(files)),
		})
	})
	r.Run(":9090")
}

注意事项:

  1. 逻辑和单文件相同
  2. 得到的同一个key下的文件存在一个切片里,因此存储时需要先遍历。

调试:

  1. 访问.../index

mark

  1. 点击登陆后,后端返回信息

mark

  1. 此时在后端服务器内文件已保存

mark

当然也可以用postman进行测试,那就不需要前端代码,后端代码中也不需要模板渲染和发送代码。

具体例子可参考 https://www.pianshen.com/article/1711189487/

猜你喜欢

转载自www.cnblogs.com/wind-zhou/p/12977510.html