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

将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条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器