-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupload.go
81 lines (72 loc) · 1.83 KB
/
upload.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
package main
import (
"io"
"net/http"
"os"
"path/filepath"
"strings"
)
const (
UploadDirectory = "./uploads"
)
func fileUploadHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Parse the multipart form with a max memory of 10MB
err := r.ParseMultipartForm(10 << 20)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
file, header, err := r.FormFile("file")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
defer file.Close()
// Check file type
if !strings.HasSuffix(header.Filename, ".csv") && !strings.HasSuffix(header.Filename, ".txt") && !strings.HasSuffix(header.Filename, ".pdf") && !strings.HasSuffix(header.Filename, ".html") {
http.Error(w, "Unsupported file type", http.StatusBadRequest)
return
}
// Save the file
err = CreateDirectoryIfNotExist("./uploads")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
filePath := filepath.Join(UploadDirectory, header.Filename)
var out *os.File
out, err = os.Create(filePath)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer out.Close()
_, err = io.Copy(out, file)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_, err = loadDocs(filePath)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_, err = w.Write([]byte("File Uploaded.Data successfully processed."))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func CreateDirectoryIfNotExist(path string) error {
if _, err := os.Stat(path); os.IsNotExist(err) {
err = os.MkdirAll(path, os.ModePerm)
if err != nil {
return err
}
}
return nil
}