forked from devfeel/dotweb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
uploadfile.go
67 lines (58 loc) · 1.31 KB
/
uploadfile.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package dotweb
import (
"errors"
files "github.com/devfeel/dotweb/framework/file"
"io"
"mime/multipart"
"os"
)
type UploadFile struct {
File multipart.File
Header *multipart.FileHeader
fileExt string //file extensions
fileName string
fileSize int64
}
func NewUploadFile(file multipart.File, header *multipart.FileHeader) *UploadFile {
return &UploadFile{
File: file,
Header: header,
fileName: header.Filename,
fileExt: files.GetFileExt(header.Filename),
}
}
// 获取文件大小的接口
type Sizer interface {
Size() int64
}
//get upload file client-local name
func (f *UploadFile) FileName() string {
return f.fileName
}
//get upload file size
func (f *UploadFile) Size() int64 {
if f.fileSize <= 0 {
if sizer, ok := f.File.(Sizer); ok {
f.fileSize = sizer.Size()
}
}
return f.fileSize
}
//save file in server-local with filename
func (f *UploadFile) SaveFile(fileName string) (size int64, err error) {
size = 0
if fileName == "" {
return size, errors.New("filename not allow empty")
}
fileWriter, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
return size, err
}
defer fileWriter.Close()
size, err = io.Copy(fileWriter, f.File)
return size, err
}
//get upload file extensions
func (f *UploadFile) GetFileExt() string {
return f.fileExt
}