## 单文件上传
```
import (
"fmt"
"github.com/gin-gonic/gin"
"psoriasis/common"
"math/rand"
"os"
"path"
"runtime"
"time"
)
func upload(){
file, err := c.FormFile("file")
if err != nil {
fmt.Println(err)
return
}
if file.Size > 1024 * 1024 *20 {
fmt.Println("上传图片大小不能超过20MB")
return
}
ext := path.Ext(file.Filename) // 文件后缀
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
// 文件名
filename := fmt.Sprintf("%06v", rnd.Int31n(1000000))
//验证后缀名是否符合要求
var AllowExtMap = map[string]bool{
".jpg":true,
".jpeg":true,
".png":true,
}
if _,ok := AllowExtMap[ext];!ok{
fmt.Println("文件类型错误")
return
}
//创建目录
uploadDir := "statics/uploads/images/" + time.Now().Format("2006/01/")
err = os.MkdirAll( uploadDir , 777)
if err != nil {
fmt.Println("没有权限创建目录")
return
}
filename := uploadDir + time.Now().Format("20060102150405") + filename + ext
// 保存文件
if err = c.SaveUploadedFile(file, filename); err != nil {
fmt.Println(err.Error())
return
}
imagePath := "http://127.0.0.1:8080"+filename
fmt.Println(imagePath)
}
```
## 多文件上传
```go
form, _ := c.MultipartForm()
files := form.File["upload[]"]
for _, file := range files {
log.Println(file.Filename)
// 上传文件至指定目录
// c.SaveUploadedFile(file, filename)
}
```
## 七牛云上传
```go
import (
"context"
"fmt"
"github.com/gin-gonic/gin"
"github.com/qiniu/api.v7/v7/auth/qbox"
"github.com/qiniu/api.v7/v7/storage"
"project/config"
"path"
)
func UploadFile(c *gin.Context){
file, _ := c.FormFile("file")
f, _ := file.Open()
fmt.Println(f)
//return
if file.Size > 1024 * 1024 *10 {
fmt.Printf("文件大小不能超过10M")
return
}
ext := path.Ext(file.Filename)
//验证后缀名是否符合要求
var AllowExtMap = map[string]bool{
".jpg":true,
".jpeg":true,
".png":true,
}
if _,ok := AllowExtMap[ext];!ok{
fmt.Printf("文件类型错误")
return
}
putPolicy := storage.PutPolicy{
Scope: config.Bucket,
}
mac := qbox.NewMac(config.AccessKey, config.SecretKey)
upToken := putPolicy.UploadToken(mac)
cfg := storage.Config{}
// 空间对应的机房
cfg.Zone = &storage.ZoneHuanan
// 是否使用https域名
cfg.UseHTTPS = true
// 上传是否使用CDN上传加速
cfg.UseCdnDomains = false
// 构建表单上传的对象
formUploader := storage.NewFormUploader(&cfg)
ret := storage.PutRet{}
// 可选配置
putExtra := storage.PutExtra{}
err := formUploader.PutWithoutKey(context.Background(), &ret, upToken, f, file.Size, &putExtra)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(ret.Key, ret.Hash)
}
```