go run server.go
curl -v -H 'Content-Type: multipart/form-data' -F "uploadfile=@./sample_video.mp4" -k http://localhost:8080/upload
| package main | |
| import ( | |
| "encoding/json" | |
| "fmt" | |
| "io" | |
| "net/http" | |
| "os" | |
| "time" | |
| ) | |
| type fileData struct { | |
| File string `json:"file"` | |
| } | |
| func main() { | |
| http.HandleFunc("/", hello) | |
| http.HandleFunc("/upload", handleUpload) | |
| http.ListenAndServe(":8080", nil) | |
| } | |
| func hello(w http.ResponseWriter, r *http.Request) { | |
| w.Write([]byte("hello!")) | |
| } | |
| func handleUpload(w http.ResponseWriter, r *http.Request) { | |
| const maxUploadSize = 2 * 1024 * 1024 // 2MB | |
| fmt.Printf("maxUploadSize: %v, headerContentLength: %v", maxUploadSize, r.Header.Get("Content-Length")) | |
| r.Body = http.MaxBytesReader(w, r.Body, maxUploadSize) | |
| if err := r.ParseMultipartForm(maxUploadSize); err != nil { | |
| panic(err) | |
| } | |
| file, handler, err := r.FormFile("uploadfile") | |
| if err != nil { | |
| panic(err) | |
| } | |
| defer file.Close() | |
| filepath := "./" + time.Now().Format("20060102_150405") + "_" + handler.Filename | |
| f, err := os.OpenFile(filepath, os.O_WRONLY|os.O_CREATE, 0666) | |
| if err != nil { | |
| panic(err) | |
| } | |
| defer f.Close() | |
| io.Copy(f, file) | |
| w.Header().Set("Content-Type", "application/json; charset=utf-8") | |
| json.NewEncoder(w).Encode(fileData{filepath}) | |
| } |