Skip to content

Commit a7c62a1

Browse files
committed
small addition of file upload functionality
1 parent 1482d29 commit a7c62a1

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

gomgo.go

+43
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@ package main
22

33
import (
44
"encoding/json"
5+
"fmt"
6+
"io/ioutil"
57
"log"
8+
"mime/multipart"
69
"net/http"
710
"time"
811

@@ -122,6 +125,45 @@ func Handler() string {
122125
return "Index"
123126
}
124127

128+
//UploadHandler is a sample function to upload a file
129+
func UploadHandler(res http.ResponseWriter, req *http.Request) {
130+
file, handle, err := req.FormFile("file")
131+
if err != nil {
132+
fmt.Fprintf(res, "%v", err)
133+
return
134+
}
135+
defer file.Close()
136+
mimeType := handle.Header.Get("Content-Type")
137+
switch mimeType {
138+
case "image/jpeg":
139+
saveFile(res, file, handle)
140+
case "image/png":
141+
saveFile(res, file, handle)
142+
default:
143+
jsonResponse(res, http.StatusBadRequest, "The format file is not valid.")
144+
}
145+
}
146+
147+
func saveFile(res http.ResponseWriter, file multipart.File, handle *multipart.FileHeader) {
148+
data, err := ioutil.ReadAll(file)
149+
if err != nil {
150+
fmt.Fprintf(res, "%v", err)
151+
return
152+
}
153+
err = ioutil.WriteFile("./files/"+handle.Filename, data, 0666)
154+
if err != nil {
155+
fmt.Fprintf(res, "%v", err)
156+
return
157+
}
158+
jsonResponse(res, http.StatusCreated, "File Uploaded")
159+
}
160+
161+
func jsonResponse(res http.ResponseWriter, code int, message string) {
162+
res.Header().Set("Content-Type", "application/json")
163+
res.WriteHeader(code)
164+
fmt.Fprint(res, message)
165+
}
166+
125167
func main() {
126168
m := martini.Classic()
127169
m.Get("/", Handler)
@@ -130,6 +172,7 @@ func main() {
130172
m.Get("/getname/:id", IDHandler)
131173
m.Put("/updatenames/:id", UpdateHandler)
132174
m.Delete("/deletename/:id", DeleteHandler)
175+
m.Post("/upload", UploadHandler)
133176
log.Println("Connecting to MongoDB")
134177
Session, err = mgo.Dial("localhost")
135178
if err != nil {

0 commit comments

Comments
 (0)