-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
53 lines (44 loc) · 1.13 KB
/
main.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
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func uploadFile(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Uploading File\n")
// 1. parse input, type multipart/form-data.
r.ParseMultipartForm(10 << 20)
// 2. retrieve file from posted form-data
file, handler, err := r.FormFile("myFile")
if err != nil {
fmt.Println("Error Retrieving file from form-data")
fmt.Println(err)
return
}
defer file.Close()
fmt.Printf("Uploaded File: %+v\n", handler.Filename)
fmt.Printf("File Size: %+v\n", handler.Size)
fmt.Printf("MIME Header: %+v\n", handler.Header)
// 3. write temporary file on our server
tempFile, err := ioutil.TempFile("temp-images", "upload-*.png")
if err != nil {
fmt.Println(err)
return
}
defer tempFile.Close()
fileBytes, err := ioutil.ReadAll(file)
if err != nil {
fmt.Println(err)
}
tempFile.Write(fileBytes)
// 4. return whether or not this has been successful
fmt.Fprintf(w, "Successfully Uploaded File\n")
}
func setupRoutes() {
http.HandleFunc("/upload", uploadFile)
http.ListenAndServe(":8080", nil)
}
func main() {
fmt.Println("Go File Upload Tutorial")
setupRoutes()
}