In order to save videos uploaded through json, I came up with this function:
func SaveBase64VidToDisk(vidString string) (interface{}, error) {
vidExt := strings.ToLower(strings.Split(strings.Split(vidString, ";")[0], "/")[1])
vidData := strings.Split(vidString, ";base64,")[1]
vidReader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(vidData))
fmt.Println("vidEXT is:", videExt)
dir, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
destDir := "/media/videos/"
path := dir + destDir
vidFileName := getRandomFileName("randomstr") + "." + vidExt
vidFile, err := os.Create(path + vidFileName)
if err != nil {
fmt.Println(err)
return nil, err
}
defer vidFile.Close()
if _, err := vidFile.Write(vidData); err != nil {
fmt.Println("error saving video")
panic(err)
return nil, nil
}
return vidFileName, nil
}
func getRandomFileName(prefix string) string {
rand.Seed(time.Now().UTC().UnixNano())
l := len(prefix)
result := make([]byte, l)
for i := 0; i < l; i++ {
result[i] = CHARS[rand.Intn(len(CHARS))]
}
return string(result)
}
However this gives the error:
shared/saveimage.go:117: cannot use vidData (type string) as type []byte in argument to vidFile.Write
admittedly I don't know what decoder should I use to save the data so SaveBase64VidToDisk
is a shut in the dark, so appreciate your help to fix this.