go框架之gin上传文件
2021-08-22 本文已影响0人
IT小池
创建接口:
func main() {
r := gin.Default()
r.POST("/upload",upload)
r.Run()
}
// upload 上传
func upload(c *gin.Context) {
file, err := c.FormFile("file")
if err != nil {
fmt.Printf("111111111upload error:%v \n",err)
return
}
ext := strings.Split(file.Filename, ".")
if !Container(ext[1],[...]string{"jpg","png"}){
c.JSON(http.StatusOK,gin.H{"code":1,"msg":"文件格式不支持!"})
return
}
filePath := fmt.Sprintf("./img/%s/",time.Now().Format("2006/01/02"))
_, err = os.Stat(filePath)
if err != nil {
if !os.IsExist(err) { // 目录不存在,创建目录
err := os.MkdirAll(filePath, os.ModePerm)
if err != nil {
fmt.Println(err)
return
}
}
}
filePath = filePath + file.Filename;
err = c.SaveUploadedFile(file, filePath)
if err != nil {
fmt.Printf("upload error:%v \n",err)
return
}
c.JSON(http.StatusOK,gin.H{"msg":"ok","path":filePath})
}
// container 判断 target 中是否包含 obj
func container(obj interface{},target interface{}) bool {
targetValue := reflect.ValueOf(target)
switch reflect.TypeOf(target).Kind() {
case reflect.Array,reflect.Slice:
for i := 0; i < targetValue.Len(); i++ {
if targetValue.Index(i).Interface() == obj {
return true
}
}
case reflect.Map:
if targetValue.MapIndex(reflect.ValueOf(obj)).IsValid() {
return true
}
}
return false
}