将base64编码的字符串视频保存到磁盘

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.

This won't work as vidData is a string containing the base64 encoded video. What you want is to read the data from vidReader, and save that. It's an io.Reader so you can use the Read function to read data from it.

Alternatively, use the Decode String function in the base64 package to read it straight into a []byte.

data, _ := base64.StdEncoding.DecodeString(vidData)
vidFile.Write(data)

You can probably just do

vidFile.Write([]byte(vidData))

Edit: Oh, I see, I thought you literally wanted to save the video base64encoded. Sounds like you want to do:

data := []byte{}
base64.StdEncoding.Decode(data, vidData)
vidFile.Write(data)