Gin文件上传

Gin文件上传

一 上传文件

1.1 上传单个文件

  • multipart/form-data格式用于文件上传
  • gin文件上传与原生的net/http方法类似,不同在于gin把原生的request封装到c.Request中
package main

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

func main() {
	r := gin.Default()
	//限制上传最大尺寸 8 M,默认:gin.defaultMultipartMemory,32M
  // 8*2的20次方:8388608b也就是8M
	r.MaxMultipartMemory = 8 << 20
	r.POST("/upload", func(c *gin.Context) {
		file, err := c.FormFile("file")
		if err != nil {
			c.String(500, "上传图片出错")
		}
    // 上传文件到指定的目录,在项目根路径下创建/media/upload文件夹
		dst := path.Join("./media/upload", file.Filename)
		fmt.Println(dst)
		c.SaveUploadedFile(file,dst)
		c.String(http.StatusOK, file.Filename)
	})
	r.Run()
}

1.2 上传多个文件之不同名

package main

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

func main() {
	router := gin.Default()

	router.MaxMultipartMemory = 8 << 20
	router.POST("/upload", func(c *gin.Context) {
		file1, _ := c.FormFile("file1")
		file2, _ := c.FormFile("file2")
       
		dst1 := path.Join("./media/upload", file1.Filename)
		c.SaveUploadedFile(file1,dst1)

		dst2 := path.Join("./media/upload", file2.Filename)
		c.SaveUploadedFile(file2,dst2)
		c.String(http.StatusOK, "文件上传成功")
	})
	router.Run(":8000")
}

1.3 上传多个文件之同名

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"path"
)

func main() {
	router := gin.Default()

	router.MaxMultipartMemory = 8 << 20
	router.POST("/upload", func(c *gin.Context) {
		form, err := c.MultipartForm()
		if err != nil {
			c.String(http.StatusBadRequest, fmt.Sprintf("get err %s", err.Error()))
		}
		// 获取所有图片
		files := form.File["files"]
		// 遍历所有图片
		for _, file := range files {
			// 上传文件至指定目录
			dst := path.Join("./media/upload", file.Filename)
			if err := c.SaveUploadedFile(file, dst); err != nil {
				c.String(http.StatusBadRequest, fmt.Sprintf("上传失败 %s", err.Error()))
				return
			}
		}
		c.String(200, fmt.Sprintf("上传 %d 个文件", len(files)))
	})
	router.Run(":8000")
}

1.4 上传多个图片-按照归档存储

package main

import (
	"fmt"
	"gin_test/utils"
	"github.com/gin-gonic/gin"
	"log"
	"os"
	"path"
	"strconv"
)

func main() {
	router := gin.Default()

	router.MaxMultipartMemory = 8 << 20
	router.POST("/upload", func(c *gin.Context) {
		file, _ := c.FormFile("file")
		//2、获取后缀名 判断类型是否正确 .jpg .png .gif .jpeg .md
		extName := path.Ext(file.Filename) //获取后缀名
		allowExtMap := map[string]bool{
			".jpg":  true,
			".png":  true,
			".gif":  true,
			".jpeg": true,
			".md": true,
		}

		if _, ok := allowExtMap[extName]; !ok {
			c.String(200, "文件类型不合法")
			return
		}
		//3、创建图片保存目录 static/upload/20200623
		day := utils.GetDay()
		dir := "./media/" + day
		if err := os.MkdirAll(dir, 0777); err != nil {
			log.Println(err)
		}
		//4、生成文件名称 1649450399.md
		fileUnixName := strconv.FormatInt(utils.GetUnix(), 10)
		saveDir := path.Join(dir, fileUnixName+extName) // media/upload/20220409/1649450399.md
		fmt.Println(saveDir)
		c.SaveUploadedFile(file, saveDir)
		c.String(200, "上传文件成功")
	})
	router.Run(":8000")
}
utils/common.go
package utils

import (
	"crypto/md5"
	"fmt"
	"time"
)

//时间戳间戳转换成日期
func UnixToDate(timestamp int) string {
	t := time.Unix(int64(timestamp), 0)
	return t.Format("2006-01-02 15:04:05")
}

//日期转换成时间戳 2006-01-02 15:04:05
func DateToUnix(str string) int64 {
	template := "2006-01-02 15:04:05"
	t, err := time.ParseInLocation(template, str, time.Local)
	if err != nil {
		return 0
	}
	return t.Unix()
}
func GetUnix() int64 {
	return time.Now().Unix()
}
func GetDate() string {
	template := "2006-01-02 15:04:05"
	return time.Now().Format(template)
}
func GetDay() string {
	template := "20060102"
	return time.Now().Format(template)
}
func Md5(str string) string {
	data := []byte(str)
	return fmt.Sprintf("%x\n", md5.Sum(data))
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

go&Python

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值