iedc-go/dri/upload/upload.go
2022-03-13 01:48:54 +08:00

71 lines
1.5 KiB
Go

package upload
import (
. "code.hoteas.com/golang/hotime/common"
"errors"
"io"
"mime/multipart"
"net/http"
"os"
"strings"
"time"
)
type Upload struct {
Path string
}
func (that *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 = that.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") + ObjToStr(Rand(6))
filePath = path + "/" + filename + that.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
}