结构讲解
后端代码
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
router.LoadHTMLFiles("./view/index.html", "./view/upload.html")
//加载静态资源,例如网页的css、js
router.Static("/static", "./static")
//加载静态资源,一般是上传的资源,例如用户上传的图片
router.StaticFS("/upload", http.Dir("upload"))
//加载单个静态文件
router.StaticFile("/favicon.ico", "./static/favicon.ico")
router.GET("/", func(context *gin.Context) {
context.HTML(http.StatusOK, "index.html", nil)
})
router.POST("/upload", func(context *gin.Context) {
file, _ := context.FormFile("file")
// 上传文件至指定目录
if err := context.SaveUploadedFile(file, "./upload/"+file.Filename); err != nil {
fmt.Println(err)
}
context.HTML(http.StatusOK, "upload.html", gin.H{"file": "/upload/" + file.Filename})
})
router.Run(":8080")
}
文件上传页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
<link href="/static/css/index.css" rel="stylesheet">
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
</body>
</html>
图片展示页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<img src="{{.file}}">
</body>
</html>
上传成功后,图片的访问地址http://127.0.0.1:8080/upload/2377654-3266b552b19aeb26.png
链接:https://pan.baidu.com/s/10fVlywK77D5Pgr0bjuQVjg
提取码:ssol