当前位置:网站首页>GIN file upload and return

GIN file upload and return

2022-08-09 13:47:00 One Leaf Knows Autumn @qqy

前言

感谢开源项目gin-vue-admin,以及1010Workshop tutorial,项目文档
I'm just following along,Then just take notes,New code may be added,But the essence is still a process of learning.

上传文件

使用postman模拟上传文件
无论使用postmanOr the front-end students upload files directly,Both need to be used in the request headerContent-Type来告知,i.e. with valuemultipart/form-data来进行上传文件
在这里插入图片描述

form-data传参

此时在postThe request is no longer availablejson了,要使用form-data.
此时在postmanThe request parameter body in ,Body中新建一个key,名为file(可以任意一个key),Then set its file format to File,The file format used at this time,换成字符串Text也是允许的.
在这里插入图片描述
如果选择的是Text,在后面的ValueJust fill in the string directly,这里选则的是File,所以在后面Value的位置,Click to select files,Perform the operation of simulating file transfer.
在这里插入图片描述
Just choose a text file to view the effect to use
点击打开
在这里插入图片描述
在golandType the following code in and run it:

package main

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


func main() {
    
	r := gin.Default() //启动gin路由,Start with basic middleware logger and recovery (crash-free) 中间件
	r.POST("testUpload", func(c *gin.Context) {
    
		file, _ := c.FormFile("file")
		c.JSON(200, gin.H{
    
			"msg":file,
		})
	})
	r.Run(":1010") // listen and serve on 0.0.0.0:8080
}

发起postman的请求:

在这里插入图片描述
在这里插入图片描述
可以看出,Although the returned things can not be understood,But it has returned successfully

保存文件

在goland中的返回JSONAdd the following statement before,Realize the storage of received files,Here is to save the received file in the current path,and use the same filename as when uploading.

func main() {
    
	r := gin.Default() //启动gin路由,Start with basic middleware logger and recovery (crash-free) 中间件
	r.POST("testUpload", func(c *gin.Context) {
    
		file, _ := c.FormFile("file")
		c.SaveUploadedFile(file, "./"+file.Filename)
		c.JSON(200, gin.H{
    
			"msg":file,
		})
	})
	r.Run(":1010") // listen and serve on 0.0.0.0:8080
}

然后使用postmanInitiate an upload file request again,
在这里插入图片描述
在这里插入图片描述
The file has been saved,And after comparison with the uploaded file is no different
此处给出gin框架SaveUploadedFile实现的源码

// SaveUploadedFile uploads the form file to specific dst.
func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error {
    
	src, err := file.Open()
	if err != nil {
    
		return err
	}
	defer src.Close()

	out, err := os.Create(dst)
	if err != nil {
    
		return err
	}
	defer out.Close()

	_, err = io.Copy(out, src)
	return err
}

Then implement this part in your own way

func main() {
    
	r := gin.Default() //启动gin路由,Start with basic middleware logger and recovery (crash-free) 中间件
	r.POST("testUpload", func(c *gin.Context) {
    
		file, _ := c.FormFile("file")
		in, _ := file.Open()
		defer in.Close()
		out, _ := os.Create("./"+file.Filename)
		defer out.Close()
		io.Copy(out, in)

		c.JSON(200, gin.H{
    
			"msg":file,
		})
	})
	r.Run(":1010") // listen and serve on 0.0.0.0:8080
}

Here is the same effect as above,Do not repeat the presentation

附加参数

Forms are used here,Then the form parameters learned before are still applicable here.
Change the code,增加name参数:

func main() {
    
	r := gin.Default() //启动gin路由,Start with basic middleware logger and recovery (crash-free) 中间件
	r.POST("testUpload", func(c *gin.Context) {
    
		file, _ := c.FormFile("file")
		name := c.PostForm("name")
		in, _ := file.Open()
		defer in.Close()
		out, _ := os.Create("./"+file.Filename)
		defer out.Close()
		io.Copy(out, in)

		c.JSON(200, gin.H{
    
			"msg":file,
			"name":name,
		})
	})
	r.Run(":1010") // listen and serve on 0.0.0.0:8080
}

在postman中增加name参数,并发起请求
在这里插入图片描述
在这里插入图片描述
Not only successfully got the file,还将nameparameters are obtained
通过这种方式,You can mix files and other information to the background
You can also upload pictures here,Because the data is transmitted in the form of a stream when it is traced back to the bottom,所以本质是一样的

Return the file to the frontend

单个文件

Make changes to the code

func main() {
    
	r := gin.Default() //启动gin路由,Start with basic middleware logger and recovery (crash-free) 中间件
	r.POST("testUpload", func(c *gin.Context) {
    
		file, _ := c.FormFile("file")
		in, _ := file.Open()
		defer in.Close()
		out, _ := os.Create("./"+file.Filename)
		defer out.Close()
		io.Copy(out, in)
		c.Writer.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=%s", file.Filename))
		c.File("./"+file.Filename)
	})
	r.Run(":1010") // listen and serve on 0.0.0.0:8080
}

这里先直接给出postman请求结果
在这里插入图片描述
Give the picture again
在这里插入图片描述
函数c.Writer.Header().Add()Expand later

批量文件

将代码修改如下:

func main() {
    
	r := gin.Default() //启动gin路由,Start with basic middleware logger and recovery (crash-free) 中间件
	r.POST("testUpload", func(c *gin.Context) {
    
		form,_ := c.MultipartForm()
		file := form.File["file"]
		fmt.Println(file)
	})
	r.Run(":1010") // listen and serve on 0.0.0.0:8080
}

Here is just a rough experience,具体实现就不给出了
postman进行请求
在这里插入图片描述
It can be found here in the form of two streams,Because there is no set return,所以postmanNothing is displayed in
Change the code again for more visual observation,增加一部分

func main() {
    
	r := gin.Default() //启动gin路由,Start with basic middleware logger and recovery (crash-free) 中间件
	r.POST("testUpload", func(c *gin.Context) {
    
		form,_ := c.MultipartForm()
		file := form.File["file"]
		fmt.Println(file)
		for _, f := range file{
    
			log.Println(f.Filename)
		}
	})
	r.Run(":1010") // listen and serve on 0.0.0.0:8080
}

在这里插入图片描述Multiple files can be stored by looping,Because when looping through,Each pass is equivalent to processing a single file

原网站

版权声明
本文为[One Leaf Knows Autumn @qqy]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/221/202208091244282125.html