达成效果:同过实现在网页上点击上传功能,将文件上传至本机C盘下tmp目录功能,初探gin框架,了解gin的方法调用和html模板库使用。
一、目录结构
- cmd/upload/
- cmd/upload/main.go //实现主函数
- cmd/upload/templates/ //该目录下放网页html文件
- cmd/upload/templates/index.html
二、实现
<!--index.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>{{.title}}</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="f1">
<input type="submit" value="上传">
</form>
</body>
</html>
// main.go
package main
import (
"fmt"
"log"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
// 处理multipart forms提交文件时默认的内存限制是32 MiB
// 可以通过下面的方式修改
// r.MaxMultipartMemory = 8 << 20 // 8 MiB
//注意点:
//Gin 框架中使用 c.HTML 可以渲染模板,渲染模板前需要使用 LoadHTMLGlob() 或者 LoadHTMLFiles() 方法加载模板。
r.LoadHTMLGlob("templates/*")
r.POST("/upload", func(c *gin.Context) {
// 单个文件
file, err := c.FormFile("f1")
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
log.Println(file.Filename)
dst := fmt.Sprintf("C:/tmp/%s", file.Filename)
// 上传文件到指定的目录
c.SaveUploadedFile(file, dst)
c.JSON(http.StatusOK, gin.H{
"message": fmt.Sprintf("'%s' uploaded!", file.Filename),
})
})
//方法一:http重定向
// 和方法二的区别:方法一地址会变为重定向后的,方法二地址不变
r.GET("/", func(ctx *gin.Context) {
// 重定向,状态码必须是http.StatusMovedPermanently
ctx.Redirect(http.StatusMovedPermanently, "/index")
})
// 方法二:路由重定向,此处注意,不能是/,和方法一不能同时使用
//r.GET("/ttt", func(ctx *gin.Context) {
// 指定重定向的URL
// ctx.Request.URL.Path = "/index"
// r.HandleContext(ctx)
//})
r.GET("/index", func(ctx *gin.Context) {
ctx.HTML(http.StatusOK, "index.html", gin.H{
"title": "文件上传",
})
})
r.Run(":80")
}
三、使用
在浏览器上访问如下链接即可
http://localhost/
或
http://localhost/index