当前位置:网站首页>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
边栏推荐
猜你喜欢
FFmpeg多媒体文件处理(ffmpeg操作目录及list的实现)
2022年非一线IT行业就业前景?
在“Extend the Omniverse”比赛中构建用于 3D 世界的工具
jenkins api create custom pipeline
Periodic sharing of Alibaba Da Tao system model governance
GIN中GET POST PUT DELETE请求
Jenkins API groovy调用实践: Jenkins Core Api & Job DSL创建项目
绘制混合密度函数图以及添加分位数线
FFmpeg多媒体文件处理(ffmpeg处理流数据的基本概念)
5G China unicom general exception handling
随机推荐
Dry+Bean+Dataset R语言数据分析,报告英文
驻波比计算方法
乐东消防救援大队应邀为干部开展消防安全培训
Rmarkdown教程
Anta and Huawei Sports Health jointly verify the champion running shoes and lead Chinese sports with innovation
Flutter Getting Started and Advanced Tour (3) Text Widgets
GIN文件上传与返回
如何修改data work上jdbc驱动的版本
Customize VIEW to realize in-app message reminder to rotate up and down
Bitmaps and bit operations
SQL Server查询优化 (转载非原创)
安踏携手华为运动健康共同验证冠军跑鞋 创新引领中国体育
JVM之配置介绍(一)
激光熔覆在农机修复强化中的应用及研究方向
ctfshow七夕杯2022
[FPGA Tutorial Case 48] Image Case 8 - Realization of Converting RGB Image to HSV Image Based on FPGA, Assisted Verification by MATLAB
ERP不规范,同事两行泪 (转载非原创)
ansible-cmdb friendly display ansible collects host information
从NPU-SLAM-EDA技术分析
Flutter introduction advanced trip (5) Image Widget