-
Notifications
You must be signed in to change notification settings - Fork 0
/
uploader.go
67 lines (58 loc) · 1.32 KB
/
uploader.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 rider
//思路来源,大神dotweb的框架:更多框架信息=>
import (
"errors"
"io"
"mime/multipart"
"os"
"strings"
"github.com/hypwxm/rider/utils/file"
)
type UploadFile struct {
File multipart.File
header *multipart.FileHeader
Ext string
Name string
size int64
}
func NewUploadFile(f multipart.File, header *multipart.FileHeader) *UploadFile {
return &UploadFile{
File: f,
header: header,
Name: header.Filename,
Ext: file.Ext(header.Filename),
}
}
// 获取文件大小的接口
type size interface {
Size() int64
}
// 获取文件信息的接口
type Stat interface {
Stat() (os.FileInfo, error)
}
//获取上传的文件大小,具体需要的时候在进行赋值
func (f *UploadFile) Size() int64 {
if f.size <= 0 {
if statInterface, ok := f.File.(Stat); ok {
fileInfo, _ := statInterface.Stat()
f.size = fileInfo.Size()
}
if sizer, ok := f.File.(size); ok {
f.size = sizer.Size()
}
}
return f.size
}
//存储http请求的文件到服务器
func (f *UploadFile) StoreFile(filename string) (size int64, err error) {
if strings.TrimSpace(filename) == "" {
return 0, errors.New("filename cannot be empty")
}
fw, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
return 0, err
}
defer fw.Close()
return io.Copy(fw, f.File)
}