-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile.go
More file actions
68 lines (61 loc) · 1.55 KB
/
file.go
File metadata and controls
68 lines (61 loc) · 1.55 KB
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
68
package web
import (
"io"
"log"
"mime/multipart"
"net/http"
"os"
"path/filepath"
)
type FileUploader struct {
FileField string
DstPathFunc func(fh *multipart.FileHeader) string
}
func (f *FileUploader) Handle() HandlerFunc {
return func(ctx *Context) {
src, srcHeader, err := ctx.Req.FormFile(f.FileField)
if err != nil {
ctx.RespStatusCode = 400
ctx.RespData = []byte("上传失败,未找到数据")
log.Fatalln(err)
return
}
defer src.Close()
dst, err := os.OpenFile(f.DstPathFunc(srcHeader),
os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o666)
if err != nil {
ctx.RespStatusCode = 500
ctx.RespData = []byte("上传失败")
log.Fatalln(err)
return
}
defer dst.Close()
_, err = io.CopyBuffer(dst, src, nil)
if err != nil {
ctx.RespStatusCode = 500
ctx.RespData = []byte("上传失败")
log.Fatalln(err)
return
}
ctx.RespData = []byte("上传成功")
}
}
type FileDownloader struct {
Dir string
}
func (f *FileDownloader) Handle() HandlerFunc {
return func(ctx *Context) {
req, _ := ctx.QueryValue("file").String()
path := filepath.Join(f.Dir, filepath.Clean(req))
fn := filepath.Base(path)
header := ctx.Resp.Header()
header.Set("Content-Disposition", "attachment;filename="+fn)
header.Set("Content-Description", "File Transfer")
header.Set("Content-Type", "application/octet-stream")
header.Set("Content-Transfer-Encoding", "binary")
header.Set("Expires", "0")
header.Set("Cache-Control", "must-revalidate")
header.Set("Pragma", "public")
http.ServeFile(ctx.Resp, ctx.Req, path)
}
}