实现数据的上传的功能

该博客展示了如何使用Gin框架处理文件上传,包括单文件和多文件上传,以及验证文件类型。同时,文章还涵盖了后端路由设置、中间件的使用以及前端表单提交的HTML代码。通过这些内容,读者可以了解到如何在Go语言中实现在Web应用中上传和管理用户头像。
摘要由CSDN通过智能技术生成

实现数据的上传的功能

代码(代码太多了,所以选择了一些主要的):
后端:
代码一:

package admin

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"path"
	"strconv"
	"webproject1/models"
)

type UserController struct{}

func (con UserController) Index(context *gin.Context) {
	context.String(200, "我是管理用户页面")
}
func (con UserController) Add(context *gin.Context) {
	context.HTML(http.StatusOK, "admin/useradd.html", gin.H{})
}
func (con UserController) Edit(context *gin.Context) {
	context.HTML(200, "admin/useredit.html", gin.H{})
}
func (con UserController) DoUpload(context *gin.Context) {
	username := context.PostForm("username")
	file, err := context.FormFile("face1")
	if err == nil {
		extName := path.Ext(file.Filename)
		allowExMap := map[string]bool{
			".jpg":  true,
			".png":  true,
			".gif":  true,
			".jpeg": true,
		}
		_, ok := allowExMap[extName]
		if !ok {
			context.String(200, "上传文件类型错误")
			return
		}
		day := models.GetDay()
		dir := "./static/upload/" + day
		err := os.MkdirAll(dir, 0666)
		if err != nil {
			fmt.Println(err)
			context.String(200, "MKdirAll失败")
			return
		}
		fileName := strconv.FormatInt(models.GetUnix(), 10) + extName
		dst := path.Join(dir, fileName)
		context.SaveUploadedFile(file, dst)
	}
	context.JSON(http.StatusOK, gin.H{
		"success":  true,
		"username": username,
	})
}
func (con UserController) DoEdit(context *gin.Context) {
	context.String(200, "执行上传")
	username := context.PostForm("username")
	face1, err1 := context.FormFile("face1")
	dst1 := path.Join("./static/upload", face1.Filename)

	if err1 == nil {
		context.SaveUploadedFile(face1, dst1)
	}
	face2, err2 := context.FormFile("face2")
	dst2 := path.Join("./static/upload", face2.Filename)
	if err2 == nil {

		context.SaveUploadedFile(face2, dst2)
	}
	context.JSON(http.StatusOK, gin.H{
		"success":  true,
		"username": username,
		"dst1":     dst1,
		"dst2":     dst2,
	})
}

路由组的:

package routers

import (
	"github.com/gin-gonic/gin"
	"webproject1/controllers/admin"
	"webproject1/middlewares"
)

func AdminRoutersInit(eng *gin.Engine) {
	adminRouters := eng.Group("/admin", middlewares.InitMiddleware)
	{
		adminRouters.GET("/", admin.IndexController{}.Index)
		adminRouters.GET("/article", admin.UserController{}.Index)
		adminRouters.GET("/article/add", admin.ArticleController{}.Add)
		adminRouters.GET("/article/edit", admin.ArticleController{}.Edit)
		adminRouters.GET("/user", admin.UserController{}.Index)
		adminRouters.GET("/user/add", admin.UserController{}.Add)
		adminRouters.GET("/user/edit", admin.UserController{}.Edit)
		adminRouters.POST("/user/doUpload", admin.UserController{}.DoUpload)
		adminRouters.POST("/user/doEdit", admin.UserController{}.DoEdit)

	}
}

前台的:

package qiantai

import (
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"net/http"
)

type DefaultController struct{}

func (con DefaultController) Index(context *gin.Context) {
	session := sessions.Default(context)
	session.Set("username", "z张三111")
	session.Save()
	context.SetCookie("username", "张三", 3600, "/", ".qiantai.com", false, true)
	context.HTML(http.StatusOK, "default/index.html", gin.H{
		"msg": "我是msg",
		"t":   1629788418,
	})
}
func (con DefaultController) News(context *gin.Context) {
	session := sessions.Default(context)
	username := session.Get("username")
	context.String(200, "username=%v", username)
}
func (con DefaultController) Shop(context *gin.Context) {
	username, _ := context.Cookie("username")
	context.String(200, "cookie="+username)
}
func (con DefaultController) DeleteCookie(context *gin.Context) {
	context.SetCookie("username", "张三", -1, "/", "localhost", false, true)

	context.String(200, "删除成功")
}

main代码:

package main

import (
	"fmt"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
	"html/template"
	"time"
	"webproject1/models"
	"webproject1/routers"
)

func initMiddinwareOne(context *gin.Context) {
	start := time.Now().UnixNano()
	fmt.Println("执行成功1")
	context.Next()
	end := time.Now().UnixNano()
	fmt.Println("执行1")
	fmt.Println(end - start)
}
func initMiddlewaretwo(context *gin.Context) {
	start := time.Now().UnixNano()
	fmt.Println("执行成功2")
	context.Next()
	end := time.Now().UnixNano()
	fmt.Println("执行2")
	fmt.Println(end - start)
}

type news struct {
	Title string `json :"title"`
}

func main() {
	eng := gin.Default()
	eng.SetFuncMap(template.FuncMap{
		"UnixToTime": models.UnixToTime,
	})
	eng.LoadHTMLGlob("templates/**/*")
	store := cookie.NewStore([]byte("secret111"))
	eng.Use(sessions.Sessions("mysession", store))
	routers.AdminRoutersInit(eng)
	routers.ApiRoutersInit(eng)
	routers.DefaultRoutersInit(eng)
	eng.Use(initMiddinwareOne)
	eng.GET("/middle", func(context *gin.Context) {
		time.Sleep(time.Second)
		context.String(200, "中间件")
	})
	eng.Run(":80")
}

前端代码(简便的),主要是实现功能:

{{ define "admin/useradd.html"}}
<!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>Document</title>
</head>

<body>
    <h2>文件上传</h2>
    <form action="/admin/user/doUpload" method="post" enctype="multipart/form-data">
        用户名<input type="text" name="username" />
        <br>
        <br>
        头像1:<input type="file" name="face1" />
        <br>
        <br>
        头像2:<input type="file" name="face2" />
        <br>
        <br>
        <input type="submit" value="提交">
    </form>
</body>

</html>
{{end}}

结果:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
本地:
在这里插入图片描述
可以发现图片,还有用户名上传成功。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值