天天看點

golang把base64轉圖檔,轉語音

func SavePic(photo string) string {
    log.Println("----接收圖檔----------")
    i := strings.Index(photo, ",")
    dec := base64.NewDecoder(base64.StdEncoding, strings.NewReader(photo[i+1:]))
    picName := tools.RandomStr(20) + ".jpg"
    f, err := os.Create(tools.Dir() + picName)
    if err != nil {
        log.Println(err)
    }
    defer f.Close()
    _, err = io.Copy(f, dec)
    if err != nil {
        log.Println(err)
    }
    log.Println("---圖檔接收完成------名稱是", picName)
    return picName
}      
func SaveAudio(voice string) string {
    log.Println("----接收語音----------")
    i := strings.Index(voice, ",")

    decoder := base64.NewDecoder(base64.StdEncoding, strings.NewReader(voice[i+1:]))
    fileName := tools.RandomStr(20) + `.mp3`
    // 以流式解碼
    buf := make([]byte, 2)
    // 儲存解碼後的資料
    dst := ``
    for {
        n, err := decoder.Read(buf)
        if n == 0 || err != nil {
            break
        }
        dst += string(buf[:n])
    }

    err := ioutil.WriteFile(tools.Dir()+fileName, []byte(dst), 0666)
    if err != nil {
        log.Println(err)
    }

    log.Println("----語音接收完成----------")

    return fileName
}