当前位置:网站首页>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
边栏推荐
猜你喜欢
随机推荐
novel research
基于 R 语言的深度学习——简单回归案例
R 语言 2010.1至2021.12艾滋病每月发病人数 时间序列分析
Flutter entry and advanced tour (6) Layout Widget
第六届“强网杯”全国网络安全挑战赛
Customize VIEW to realize in-app message reminder to rotate up and down
Flutter Getting Started and Advanced Tour (1) - Getting to Know Flutter
ERP不规范,同事两行泪 (转载非原创)
LnReader编译
gin的中间件和路由分组
面试题精选:神奇的斐波那契数列
在“Extend the Omniverse”比赛中构建用于 3D 世界的工具
大佬们,请教一下,我看官方文档中,sqlserver cdc只支持2012版之后的,对于sqlser
周末看点回顾|我国IPv6网络全面建成;2022昇腾AI开发者创享日·南京站成功举办…
glide工具类的简单封装
FFmpeg多媒体文件处理(ffmpeg处理流数据的基本概念)
用场景定义硬件,英码科技破解“边缘计算”密码
FFmpeg多媒体文件处理(ffmpeg操作目录及list的实现)
Jenkins API groovy calling practice: Jenkins Core Api & Job DSL to create a project
5G China unicom repeater network management protocol real-time requirements









