-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathfile.go
50 lines (40 loc) · 978 Bytes
/
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
package utils
import (
"fmt"
"io"
"mime/multipart"
"os"
"strings"
)
const PATH = "assets"
func UploadFile(file *multipart.FileHeader, path string) error {
parts := strings.Split(path, "/")
fileID := parts[1]
dirPath := fmt.Sprintf("%s/%s", PATH, parts[0])
if _, err := os.Stat(dirPath); os.IsNotExist(err) {
if err := os.MkdirAll(dirPath, 0777); err != nil {
return err
}
}
filePath := fmt.Sprintf("%s/%s", dirPath, fileID)
uploadedFile, err := file.Open()
if err != nil {
return err
}
defer uploadedFile.Close()
// Using os.Create to open the file with appropriate permissions
targetFile, err := os.Create(filePath)
if err != nil {
return err
}
defer targetFile.Close()
// Copy file contents from uploadedFile to targetFile
_, err = io.Copy(targetFile, uploadedFile)
if err != nil {
return err
}
return nil
}
func GetExtensions(filename string) string {
return strings.Split(filename, ".")[len(strings.Split(filename, "."))-1]
}