dongpan1308
2017-11-02 02:50
浏览 387
已采纳

将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.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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)
    vidFile.Write(data)
    
    评论
    解决 无用
    打赏 举报
  • 查看更多回答(1条)

相关推荐 更多相似问题