定义模板 需要在上传文件的 form 表单上面需要加入 enctype="multipart/form-data"
单文件上传
r.POST("/admin/user/doUpload", func(c *gin.Context) {
username := c.PostForm("username")
file, err := c.FormFile("face")
dst := path.Join("./static/upload", file.Filename)
if err==nil{
//成功
//存储文件到本地
c.SaveUploadedFile(file,dst)
}
c.JSON(200,gin.H{
"msg":"上传成功",
})
c.JSON(200,gin.H{
"success":true,
"username":username,
"dst":dst,
})
})
不同文件名的多文件上传
r.POST("/admin/user/doeidt", func(c *gin.Context) {
username := c.PostForm("username")
file1, err1 := c.FormFile("face1")
dst1 := path.Join("./static/upload", file1.Filename)
if err1==nil{
//成功
//存储文件到本地
c.SaveUploadedFile(file1,dst1)
}
file2, err2 := c.FormFile("face2")
dst2 := path.Join("./static/upload", file2.Filename)
if err2==nil{
//成功
//存储文件到本地
c.SaveUploadedFile(file2,dst2)
}
c.JSON(200,gin.H{
"success":true,
"username":username,
"dst1":dst1,
"dst2":dst2,
})
})
相同名字的多个文件上传
r.POST("/admin/user/doeidtnames", func(c *gin.Context) {
username := c.PostForm("username")
form, _ := c.MultipartForm()
files := form.File["face[]"]
for _, file := range files {
// 上传文件至指定目录
dst := path.Join("./static/upload", file.Filename)
c.SaveUploadedFile(file, dst)
}
c.JSON(200,gin.H{
"success":true,
"username":username,
})
})