2017-09-05 08:45:02 +00:00
|
|
|
package upload
|
|
|
|
|
|
|
|
import (
|
2020-04-29 15:02:09 +00:00
|
|
|
"code.hoteas.com/golang/hotime"
|
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 {
|
2020-02-20 06:20:56 +00:00
|
|
|
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("服务器创建头像文件夹失败")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
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 {
|
2020-02-20 06:20:56 +00:00
|
|
|
return "", errors.New("服务器创建文件失败")
|
2017-09-05 08:45:02 +00:00
|
|
|
}
|
|
|
|
_, err = io.Copy(header, file)
|
|
|
|
|
|
|
|
if err != nil {
|
2020-02-20 06:20:56 +00:00
|
|
|
return "", errors.New("服务器复制文件失败")
|
2017-09-05 08:45:02 +00:00
|
|
|
|
|
|
|
}
|
|
|
|
return filePath, nil
|
|
|
|
}
|