Gin实现文件上传
Gin实现文件上传
单文件上传
后端
package main
import (
"net/http"
"path"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.LoadHTMLGlob("templates/*")
r.MaxMultipartMemory = 8 << 20
r.GET("/upload", func(ctx *gin.Context) {
ctx.HTML(200, "upload.html", gin.H{
"msg": "ok",
})
})
r.POST("/upload", func(ctx *gin.Context) {
file, _ := ctx.FormFile("file")
dst := path.Join("./static", file.Filename)
//dst := "./" + file.Filename
ctx.SaveUploadedFile(file, dst)
ctx.String(200, "ok")
})
http.ListenAndServe(":9000", r)
}
前端
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="提交">
</form>
多文件上传
后端
package main
import (
"fmt"
"net/http"
"path"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.LoadHTMLGlob("templates/*")
r.MaxMultipartMemory = 8 << 20
r.GET("/upload", func(ctx *gin.Context) {
ctx.HTML(200, "upload.html", gin.H{
"msg": "ok",
})
})
r.POST("/upload", func(ctx *gin.Context) {
form, err := ctx.MultipartForm()
if err != nil {
fmt.Println(err)
}
files := form.File["files"]
for _, file := range files {
filename := path.Join("./static", file.Filename)
if err := ctx.SaveUploadedFile(file, filename); err != nil {
ctx.String(http.StatusBadRequest, "upload file err: %s", err.Error())
return
}
}
ctx.String(http.StatusOK, "OK")
})
http.ListenAndServe(":9000", r)
}
前端
<form action="/upload" method="post" enctype="multipart/form-data">
Files: <input type="file" name="files" multiple><br><br>
<input type="submit" value="提交">
</form>
头像上传判断格式并以日期保存
package main
import (
"fmt"
"net/http"
"os"
"path"
"strconv"
"time"
"github.com/gin-gonic/gin"
)
func GetUnix() int64 {
return time.Now().Unix()
}
func GetDay() string {
template := "20060102"
return time.Now().Format(template)
}
func main() {
r := gin.Default()
r.LoadHTMLGlob("templates/*")
r.MaxMultipartMemory = 8 << 20
r.GET("/upload", func(ctx *gin.Context) {
ctx.HTML(200, "upload.html", gin.H{
"msg": "ok",
})
})
r.POST("/upload", func(ctx *gin.Context) {
file, err := ctx.FormFile("file")
if err != nil {
fmt.Println(err)
}
//获取上传文件的后缀,判断是否为图片格式
extName := path.Ext(file.Filename)
fmt.Println(extName)
allowExtMap := map[string]bool{
".jpg": true,
".png": true,
".gif": true,
".jpeg": true,
}
if _, ok := allowExtMap[extName]; !ok {
ctx.String(500, "文件类型不合法")
return
}
//创建图片保存目录 static/yyyyymmdd
day := GetDay()
dir := "./static/" + day
if err := os.MkdirAll(dir, 0666); err != nil {
fmt.Println(err)
}
//生成时间戳文件名
fileUnixName := strconv.FormatInt(GetUnix(), 10)
saveDir := path.Join(dir, fileUnixName+extName)
ctx.SaveUploadedFile(file, saveDir)
ctx.JSON(200, gin.H{
"message": "文件上传成功",
})
})
http.ListenAndServe(":9000", r)
}
Gin实现文件上传
http://www.jcwit.com/article/509/