当前位置:网站首页>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的实现)
- 剑指 Offer 57 - II. 和为s的连续正数序列(滑动窗口)
- R 语言 2010.1至2021.12艾滋病每月发病人数 时间序列分析
- 从NPU-SLAM-EDA技术分析
- How to save Simulink simulation model as image or PDF
- 技术分享 | 接口自动化测试如何处理 Header cookie
- 使用注解将EventBus封装抽取到基类
- 中断系统结构及中断控制详解
- jenkins api create custom pipeline
- 【FPGA教程案例48】图像案例8——基于FPGA的RGB图像转化为HSV图像的实现,通过MATLAB进行辅助验证
猜你喜欢

Flutter entry and advanced tour (6) Layout Widget

Redis源码剖析之字典(dict)

第六届“强网杯”全国网络安全挑战赛

Uni - app - uview Swiper shuffling figure component, click on the links to jump (click to get the item after the row data, remove data operation)

5G Unicom Network Management Design Ideas

Redis源码剖析之跳表(skiplist)

Unicom network management protocol block diagram
![[HCIP Continuous Update] Principle and Configuration of IS-IS Protocol](/img/4f/035432ac84644c4bd46573aa0ab7cd.png)
[HCIP Continuous Update] Principle and Configuration of IS-IS Protocol

RTSP协议讲解

电脑重装系统后桌面图标如何调小尺寸
随机推荐
JVM之配置介绍(一)
R 语言 2010.1至2021.12艾滋病每月发病人数 时间序列分析
使用注解将EventBus封装抽取到基类
如何求最大公约数?
leetcode 20. Valid Parentheses 有效的括号(中等)
记录本项目中用到的系统调用与C库函数-2
read stream special attention
Do you know the difference between comments, keywords, and identifiers?
Flutter entry and advanced tour (6) Layout Widget
电脑重装系统后桌面图标如何调小尺寸
Introduction to Flutter advanced trip Dialog&Toast (10)
Explanation of RTSP protocol
基于 R 语言的判别分析介绍与实践 LDA和QDA
[FPGA Tutorial Case 48] Image Case 8 - Realization of Converting RGB Image to HSV Image Based on FPGA, Assisted Verification by MATLAB
注:检测到当前使用的ADB不是HBuilder内置或自定义ADB:PID为:9544进程名称为:adb.exe 路径为:c:\users\administrator\appdata\local\and
FFmpeg多媒体文件处理(ffmpeg处理流数据的基本概念)
The FPGA - work summary recently
腾讯发布第二代四足机器人Max,梅花桩上完成跳跃、空翻
JVM常用监控工具解释以及使用
kustomize entry example and basic syntax instructions