当前位置:网站首页>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
边栏推荐
猜你喜欢
随机推荐
glibc 内存管理模型 释放 C库内存缓存
批量读取word docx文件指定表格内容,保存在excel文件中
26. Pipeline parameter substitution command xargs
jenkins api创建自定义pipeline
剑指 Offer 57 - II. 和为s的连续正数序列(滑动窗口)
Bitmaps and bit operations
陈强教授《机器学习及R应用》课程 第十四章作业
WebView injects Js code to realize large image adaptive screen click image preview details
GIN文件上传与返回
ABP中的数据过滤器 (转载非原创)
Periodic sharing of Alibaba Da Tao system model governance
5G Unicom Network Management Design Ideas
FFmpeg多媒体文件处理(ffmpeg打印音视频Meta信息)
Rust from entry to proficient 04 - data types
#WeArePlay | 与更多开发者一起,探索新世界
单面线路板与精密多层PCB线路板区别有哪些?
大佬们,请教一下,我看官方文档中,sqlserver cdc只支持2012版之后的,对于sqlser
用场景定义硬件,英码科技破解“边缘计算”密码
Redis源码剖析之字典(dict)
5G China unicom general exception handling