go框架之gin上传文件
创建接口:
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 } } } //文件重命名 file_name := strconv.FormatInt(time.Now().Unix(),10) + strconv.Itoa(rand.Intn(999999-100000)+100000) + path.Ext(file.Filename) filePath = filePath + file.Filename; // 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 }