-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfile.go
99 lines (81 loc) · 2.3 KB
/
file.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package pine
import (
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"strings"
)
var (
ErrFileName = errors.New("could not determine file name")
)
func (c *Ctx) FormFile(key string) (multipart.File, *multipart.FileHeader, error) {
return c.Request.FormFile(key)
}
func (c *Ctx) SaveFile(file multipart.File, fh *multipart.FileHeader) error {
defer file.Close() // Ensure the file is closed after all operations.
// Extract filename from header directly, which is more reliable.
fileName := fh.Filename
if fileName == "" {
// Attempt to retrieve the file name from the "Content-Disposition" header.
disposition := fh.Header.Get("Content-Disposition")
if disposition != "" {
if idx := strings.Index(disposition, "filename="); idx != -1 {
fileName = disposition[idx+len("filename="):]
fileName = strings.Trim(fileName, "\"")
}
}
}
if fileName == "" {
return ErrFileName
}
// Set the desired file path, for example, saving all files to a specific directory.
filePath := filepath.Join(c.Server.config.UploadPath, fileName)
// Create the necessary directory structure for the file path.
if err := os.MkdirAll(filepath.Dir(filePath), 0755); err != nil {
return err
}
// Create and write to the output file.
out, err := os.Create(filePath)
if err != nil {
return err
}
defer out.Close()
// Copy file contents from the uploaded file to the destination.
if _, err = io.Copy(out, file); err != nil {
return err
}
return nil
}
func (c *Ctx) MultipartForm() *multipart.Form {
return c.Request.MultipartForm
}
func (c *Ctx) MultipartReader(key string) (*multipart.Reader, error) {
return c.Request.MultipartReader()
}
func (c *Ctx) MultipartFormValue(key string) string {
return c.Request.FormValue(key)
}
func (c *Ctx) SendFile(filePath string) error {
http.ServeFile(c.Response, c.Request, filePath)
return nil
}
func (c *Ctx) StreamFile(filePath string) error {
file, err := os.Open(filePath)
if err != nil {
fmt.Println(err)
return c.SendStatus(http.StatusInternalServerError)
}
defer file.Close()
fileInfo, err := file.Stat()
if err != nil {
fmt.Println(err)
return c.SendStatus(http.StatusInternalServerError)
}
modTime := fileInfo.ModTime()
http.ServeContent(c.Response.ResponseWriter, c.Request, filePath, modTime, file)
return nil
}