• 5Gin上传文件


    一 上传文件

    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))
    }
    
    
    

    Mac,linux平台下注意权限,先编译,sudo运行,文件夹才能顺利创建

  • 相关阅读:
    文本框textarea根据输入内容自适应高度 和输入中文和数字换行解决方法
    switch 和 if...else if 的区别
    vue中 eCharts 自适应容器
    AJAX跨域POST发送json时,会先发送一个OPTIONS预请求
    获取鼠标和元素的坐标点
    vue2 数据交互 vue-resource
    网站代码初始化
    vue2 关于ref
    事件监听
    cookie 的 写入,读取, 删除
  • 原文地址:https://www.cnblogs.com/liuqingzheng/p/16124105.html
Copyright © 2020-2023  润新知