iedc-go/dri/upload/upload.go

71 lines
1.4 KiB
Go
Raw Permalink Normal View History

2017-09-05 08:45:02 +00:00
package upload
import (
2021-05-23 23:27:41 +00:00
. "../../common"
2017-09-05 08:45:02 +00:00
"errors"
"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("上传文件失败")
2017-09-05 08:45:02 +00:00
}
}
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("服务器创建头像文件夹失败")
}
}
}
2021-05-23 23:27:41 +00:00
filename := time.Unix(int64(t), 0).Format("2006-01-02-15-22-25") + ObjToStr(Rand(6))
2017-09-05 08:45:02 +00:00
filePath = path + "/" + filename + this.Path
} else {
filePath = savePath
}
header, err := os.OpenFile(filePath, os.O_CREATE, 0666)
if err != nil {
return "", errors.New("服务器创建文件失败")
2017-09-05 08:45:02 +00:00
}
_, err = io.Copy(header, file)
if err != nil {
return "", errors.New("服务器复制文件失败")
2017-09-05 08:45:02 +00:00
}
return filePath, nil
}