github.com/EngineerKamesh/gofullstack@v0.0.0-20180609171605-d41341d7d4ee/volume2/section4/gopherfaceform/handlers/uploadvideo.go (about) 1 package handlers 2 3 import ( 4 "fmt" 5 "io" 6 "log" 7 "net/http" 8 "os" 9 "os/exec" 10 "path/filepath" 11 "strings" 12 ) 13 14 type UploadVideoForm struct { 15 FieldNames []string 16 Fields map[string]string 17 Errors map[string]string 18 } 19 20 func DisplayUploadVideoForm(w http.ResponseWriter, r *http.Request, u *UploadVideoForm) { 21 RenderTemplate(w, "./templates/uploadvideoform.html", u) 22 } 23 24 func ProcessUploadVideo(w http.ResponseWriter, r *http.Request, u *UploadVideoForm) { 25 26 file, fileheader, err := r.FormFile("videofile") 27 28 if err != nil { 29 log.Println("Encountered error when attempting to read uploaded file: ", err) 30 return 31 } 32 33 randomFileName := GenerateUUID() 34 35 if fileheader != nil { 36 37 extension := filepath.Ext(fileheader.Filename) 38 r.ParseMultipartForm(32 << 20) 39 40 defer file.Close() 41 42 videoFilePathWithoutExtension := "./static/uploads/videos/" + randomFileName 43 f, err := os.OpenFile(videoFilePathWithoutExtension+extension, os.O_WRONLY|os.O_CREATE, 0666) 44 45 if err != nil { 46 log.Println(err) 47 return 48 } 49 50 defer f.Close() 51 io.Copy(f, file) 52 53 thumbImageFilePath := videoFilePathWithoutExtension + "_thumb.png" 54 command := "ffmpeg -y -i " + videoFilePathWithoutExtension + extension + " -s 430x372 -f mjpeg -vframes 1 -ss 3 " + thumbImageFilePath 55 commandOutput, err := exec.Command("sh", "-c", command).Output() 56 fmt.Println("video thumbnail generation command output: ", commandOutput) 57 58 if err != nil { 59 log.Println(err) 60 return 61 } 62 63 m := make(map[string]string) 64 m["thumbnailPath"] = strings.TrimPrefix(videoFilePathWithoutExtension, ".") + "_thumb.png" 65 m["videoPath"] = strings.TrimPrefix(videoFilePathWithoutExtension, ".") + ".mp4" 66 67 RenderTemplate(w, "./templates/videopreview.html", m) 68 69 } else { 70 w.Write([]byte("Failed to process uploaded file!")) 71 } 72 } 73 74 func ValidateUploadVideoForm(w http.ResponseWriter, r *http.Request, u *UploadVideoForm) { 75 76 ProcessUploadVideo(w, r, u) 77 78 } 79 80 func UploadVideoHandler(w http.ResponseWriter, r *http.Request) { 81 82 u := UploadVideoForm{} 83 u.Fields = make(map[string]string) 84 u.Errors = make(map[string]string) 85 86 switch r.Method { 87 88 case "GET": 89 DisplayUploadVideoForm(w, r, &u) 90 case "POST": 91 ValidateUploadVideoForm(w, r, &u) 92 default: 93 DisplayUploadVideoForm(w, r, &u) 94 } 95 96 }