html端:
<h2>演示多个文件上传(名字一样)</h2> <form action="/admin/upload/duoupname" method="post" enctype="multipart/form-data"> 用户名:<input type="text" name="username" value="" /><br><br> 头像:<input type="file" name="face[]" /> <br> 头像2:<input type="file" name="face[]" /> <br> 头像3:<input type="file" name="face[]" /> <br> <input type="submit" value="提交" /> </form>
go 端: func (con UploadController)DuoUpName(c *gin.Context) { username := c.PostForm("username") form, _ := c.MultipartForm() files := form.File["face[]"] path1 := map[int]string{} //遍历所有图片 for i,f := range files { i := i //获取图像后缀 y := path.Ext(f.Filename) //获取时间戳 a := time.Now().Unix() //获取一个1W以内的随机数 b := rand.Intn(10000) //将时间戳的类型转换 z := strconv.FormatInt(a,10) //将随机书转换类型 x := strconv.FormatInt(int64(b),10) //写入保持位置与自定义名称,并且带上文件自带的后缀 dst := path.Join("./static/upload",z+x+y) //将图片保存到相应位置 c.SaveUploadedFile(f, dst) //图片地址dst中含有"\\",将地址中的"\\"替换后写入数据库 res := strings.Replace(dst, "\\", "/", -1) path1[i] = res
} c.JSON(http.StatusOK,gin.H{ "success":1, "username": username, "path" : path1, }) }