当前位置:网站首页>Realize the function of data uploading
Realize the function of data uploading
2022-07-02 04:30:00 【L 00】
Realize the function of uploading data
Code ( There's too much code , So I chose some main ):
Back end :
Code 1 :
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, " I am managing user pages ")
}
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, " Upload file type error ")
return
}
day := models.GetDay()
dir := "./static/upload/" + day
err := os.MkdirAll(dir, 0666)
if err != nil {
fmt.Println(err)
context.String(200, "MKdirAll Failure ")
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, " Perform upload ")
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,
})
}
Routing group :
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)
}
}
The front desk :
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 Zhang San 111")
session.Save()
context.SetCookie("username", " Zhang San ", 3600, "/", ".qiantai.com", false, true)
context.HTML(http.StatusOK, "default/index.html", gin.H{
"msg": " I am a 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", " Zhang San ", -1, "/", "localhost", false, true)
context.String(200, " Delete successful ")
}
main Code :
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(" Successful implementation 1")
context.Next()
end := time.Now().UnixNano()
fmt.Println(" perform 1")
fmt.Println(end - start)
}
func initMiddlewaretwo(context *gin.Context) {
start := time.Now().UnixNano()
fmt.Println(" Successful implementation 2")
context.Next()
end := time.Now().UnixNano()
fmt.Println(" perform 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, " middleware ")
})
eng.Run(":80")
}
The front-end code ( Simple ), It mainly realizes the function :
{
{
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> Upload files </h2>
<form action="/admin/user/doUpload" method="post" enctype="multipart/form-data">
user name <input type="text" name="username" />
<br>
<br>
Head portrait 1:<input type="file" name="face1" />
<br>
<br>
Head portrait 2:<input type="file" name="face2" />
<br>
<br>
<input type="submit" value=" Submit ">
</form>
</body>
</html>
{
{
end}}
result :
Local :
You can find pictures , And the user name was uploaded successfully .
边栏推荐
- 社交媒体搜索引擎优化及其重要性
- 初识P4语言
- 10 minutes to understand CMS garbage collector in JVM
- Pytoch yolov5 runs bug solution from 0:
- IDEA xml中sql没提示,且方言设置没用。
- Actual combat | use composite material 3 in application
- Spring recruitment of Internet enterprises: Kwai meituan has expanded the most, and the annual salary of technical posts is up to nearly 400000
- Free drawing software recommended - draw io
- 万卷共知,一书一页总关情,TVP读书会带你突围阅读迷障!
- 66.qt quick QML Custom Calendar component (supports vertical and horizontal screens)
猜你喜欢
unable to execute xxx. SH: operation not permitted
Yyds dry inventory compiler and compiler tools
[source code analysis] NVIDIA hugectr, GPU version parameter server - (1)
Federal learning: dividing non IID samples according to Dirichlet distribution
The solution to the complexity brought by lambda expression
【c语言】动态规划---入门到起立
cs架构下抓包的几种方法
Research on the security of ognl and El expressions and memory horse
Learn what definitelytyped is through the typescript development environment of SAP ui5
社交媒体搜索引擎优化及其重要性
随机推荐
IDEA xml中sql没提示,且方言设置没用。
Which insurance company has a better product of anti-cancer insurance?
Shenzhen will speed up the cultivation of ecology to build a global "Hongmeng Oula city", with a maximum subsidy of 10million yuan for excellent projects
How much can a job hopping increase? Today, I saw the ceiling of job hopping.
Playing with concurrency: what are the ways of communication between threads?
Target free or target specific: a simple and effective zero sample position detection comparative learning method
[source code analysis] NVIDIA hugectr, GPU version parameter server - (1)
Go function
Handling of inconsistency between cursor and hinttext position in shutter textfield
Www 2022 | rethinking the knowledge map completion of graph convolution network
Landing guide for "prohibit using select * as query field list"
One step implementation of yolox helmet detection (combined with oak intelligent depth camera)
Common locks in MySQL
Alibaba cloud polkit pkexec local rights lifting vulnerability
LCM of Spreadtrum platform rotates 180 °
Markdown edit syntax
阿里云polkit pkexec 本地提权漏洞
Uni app - realize the countdown of 60 seconds to obtain the mobile verification code (mobile number + verification code login function)
Ognl和EL表达式以及内存马的安全研究
[C language] basic learning notes