package upload import ( "errors" "go.hoteas.com/hotime" "io" "mime/multipart" "net/http" "os" "strings" "time" ) type Upload struct { Path string } func (this *Upload) UpFile(Request *http.Request, fieldName, savefilepath, savePath string) (string, error) { Request.ParseMultipartForm(32 << 20) var filePath string files := Request.MultipartForm.File var file multipart.File err := errors.New("") for k, _ := range files { fieldName = k file, _, err = Request.FormFile(fieldName) if err != nil { return "", errors.New("上传文件失败") } } if strings.EqualFold(savePath, "") { t := time.Now().Unix() data := time.Unix(int64(t), 0).Format("2006-01") path := "" if strings.EqualFold(savefilepath, "") { path = this.Path + data } else { path = savefilepath + data } _, err1 := os.Stat(path) if err1 != nil { if os.IsNotExist(err1) { err := os.MkdirAll(path, os.ModePerm) if err != nil { return "", errors.New("服务器创建头像文件夹失败") } } } filename := time.Unix(int64(t), 0).Format("2006-01-02-15-22-25") + hotime.ObjToStr(hotime.Rand(6)) filePath = path + "/" + filename + this.Path } else { filePath = savePath } header, err := os.OpenFile(filePath, os.O_CREATE, 0666) if err != nil { return "", errors.New("服务器创建文件失败") } _, err = io.Copy(header, file) if err != nil { return "", errors.New("服务器复制文件失败") } return filePath, nil }