Gin 上传保存文件
效果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6afa6010e4f758fe567c7140c6d0eacf.gif#pic_center)
源码
前端页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Upload Demo</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
选择一个文件上传:
<input type="file" name="file" size="50" />
<button type="submit">点击上传</button>
</form>
</body>
</html>
后台
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.LoadHTMLFiles("upload.html")
r.GET("/upload", func(c *gin.Context) {
c.HTML(http.StatusOK, "upload.html", gin.H{})
})
r.POST("/upload", func(c *gin.Context) {
file, err := c.FormFile("file")
if err != nil {
c.String(http.StatusInternalServerError, "读取file失败: "+err.Error())
return
}
fmt.Println("接收到文件: ", file.Filename)
c.SaveUploadedFile(file, file.Filename)
c.String(http.StatusOK, "上传成功!")
})
r.Run()
}