gin框架路由-⽂件上传(单个和多个)★单个⽂件上传
multipart/form-data格式⽤于⽂件上传
gin⽂件上传与原⽣的net/http⽅法类似,不同在于gin把原⽣的request封装到c.Request中
html前端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form action="localhost:8080/upload" method="post" enctype="multipart/form-data">
上传⽂件:<input type="file" name="file" >
<input type="submit" value="提交">
</form>
</body>
</html>
go后端代码:
package main
import (
"net/http"
"github/gin-gonic/gin"
)
func main() {
r := gin.Default()
//限制上传最⼤尺⼨
r.MaxMultipartMemory = 8 << 20
r.POST("/upload", func(c *gin.Context) {
file, err := c.FormFile("file")
if err != nil {
c.String(500, "上传图⽚出错")
}
// c.JSON(200, gin.H{"message": file.Header.Context})
c.SaveUploadedFile(file, file.Filename)
c.String(http.StatusOK, file.Filename)
})
r.Run()
}
★多个⽂件上传
html前端代码:
<!DOCTYPE html>
<html lang="en">
<head>前端大文件上传解决方案
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form action="localhost:8000/upload" method="post" enctype="multipart/form-data">上传⽂件:<input type="file" name="files" multiple>
<input type="submit" value="提交">
</form>
</body>
</html>
go后台代码:
package main
import (
"fmt"
"net/http"
"github/gin-gonic/gin"
)
// gin的helloWorld
func main() {
// 1.创建路由
// 默认使⽤了2个中间件Logger(), Recovery()
r := gin.Default()
// 限制表单上传⼤⼩ 8MB,默认为32MB
r.MaxMultipartMemory = 8 << 20
r.POST("/upload", func(c *gin.Context) {
form, err := c.MultipartForm()
if err != nil {
c.String(http.StatusBadRequest, fmt.Sprintf("get err %s", err.Error()))
}
// 获取所有图⽚
files := form.File["files"]
// 遍历所有图⽚
for _, file := range files {
// 逐个存
if err := c.SaveUploadedFile(file, file.Filename); err != nil {
c.String(http.StatusBadRequest, fmt.Sprintf("upload err %s", err.Error()))
return
}
}
c.String(200, fmt.Sprintf("upload ok %d files", len(files)))
})
//默认端⼝号是8080
r.Run(":8000")
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。