2017-11-02 02:50
浏览 380


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 {
    destDir := "/media/videos/"
    path := dir + destDir
    vidFileName := getRandomFileName("randomstr") + "." + vidExt
    vidFile, err := os.Create(path + vidFileName)
    if err != nil {
        return nil, err

    defer vidFile.Close()

    if _, err := vidFile.Write(vidData); err != nil {
        fmt.Println("error saving video")
        return nil, nil
    return vidFileName, nil


func getRandomFileName(prefix string) string {
    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.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongpu1331 2017-11-02 03:30

    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)
    打赏 评论
  • dsrw29618 2017-11-02 03:00

    You can probably just do


    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)
    打赏 评论

相关推荐 更多相似问题