Created
December 14, 2016 09:35
-
-
Save GGalizzi/c3a27d4b7e22da63b70978c50e5657db to your computer and use it in GitHub Desktop.
multipart upload golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io" | |
"mime/multipart" | |
"net/http" | |
"os" | |
) | |
//This is where the action happens. | |
func uploadHandler(w http.ResponseWriter, r *http.Request) { | |
w.Header().Set("Access-Control-Allow-Origin", "*") | |
switch r.Method { | |
//POST takes the uploaded file(s) and saves it to disk. | |
case "POST": | |
fmt.Printf("Upload request.") | |
//parse the multipart form in the request | |
err := r.ParseMultipartForm(100000) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusInternalServerError) | |
return | |
} | |
//get a ref to the parsed multipart form | |
m := r.MultipartForm | |
//get the *fileheaders | |
fmt.Printf("map %+v\n", m.File) | |
createFiles(w, m.File["video[]"]) | |
createFiles(w, m.File["thumb[]"]) | |
//display success message. | |
fmt.Printf("Upload successful.") | |
default: | |
w.WriteHeader(http.StatusMethodNotAllowed) | |
} | |
} | |
func main() { | |
http.HandleFunc("/upload", uploadHandler) | |
fs := http.FileServer(http.Dir(".")) | |
http.Handle("/", http.StripPrefix("/", fs)) | |
fmt.Printf("started") | |
//Listen on port 8080 | |
http.ListenAndServe(":8080", nil) | |
} | |
func createFiles(w http.ResponseWriter, files []*multipart.FileHeader) { | |
for i, _ := range files { | |
//for each fileheader, get a handle to the actual file | |
file, err := files[i].Open() | |
defer file.Close() | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusInternalServerError) | |
return | |
} | |
//create destination file making sure the path is writeable. | |
fmt.Printf("creating %v\n", files[i].Filename) | |
dst, err := os.Create("/home/ggalizzi/web_development/trabajo/vidpost/uploadtest/" + files[i].Filename) | |
defer dst.Close() | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusInternalServerError) | |
return | |
} | |
//copy the uploaded file to the destination file | |
if _, err := io.Copy(dst, file); err != nil { | |
http.Error(w, err.Error(), http.StatusInternalServerError) | |
return | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment