【问题标题】:'utf-8' codec can't decode byte 0x80 in position 28: invalid start byte“utf-8”编解码器无法解码位置 28 中的字节 0x80:无效的起始字节
【发布时间】:2023-03-09 21:41:01
【问题描述】:

我有一个 wav 文件,我将其转换为二进制文件,然后使用 C# 将其更改为 base64,然后将该 base64 字符串发布到 python 烧瓶 API,以便我可以对其进行解码并将 base64 字符串更改回 wav 文件,这样我就可以保存在文件夹中,我在下面收到此错误:

'utf-8' 编解码器无法解码位置 28 中的字节 0x80:无效起始字节

请看我下面的代码:

public static void copy_to_watch_folder(string filepath, string filename)
        {
            try
            {
                AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal);
                var destinationFolder = SSKAccess.mapped_dir_path;
                byte[] audio_file = File.ReadAllBytes(filepath);

                var s = Convert.ToBase64String(audio_file);

                string jsonData = JsonConvert.SerializeObject(new { Result = "OK", File = s, FileName = filename, token= SSKAccess.token }, Formatting.None);

                StringContent sC2 = new StringContent(jsonData, System.Text.Encoding.UTF8, "application/json");

                HttpClient client = new HttpClient();

                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                client.BaseAddress = new Uri(ConnectionSetup.connectionStr);

                try
                {
                    var response = client.PostAsync("putWavFile", sC2).Result;

                    if (response.IsSuccessStatusCode)
                    {
                        Logs.WriteToFile($"{ DateTime.Now } : {response.Content.ReadAsStringAsync()}");
                    }
                }
                catch (Exception exc)
                {
                    Logs.WriteToFile($"HttpError : {exc.Message}");
                }

                //System.IO.File.Copy(filepath, $"{destinationFolder}{filename}", true);
            }
            catch (IOException copyError)
            {
                Logs.WriteToFile($"{DateTime.Now} - CopyError: {copyError.Message}");
            }

        }

我的 Python 代码如下所示:

@app.route('/api/Call/putWavFile', methods=['POST'])
def PutWavFile():
    if not request.json or not 'token' in request.json: 
        abort(400)
    
    try:
        filename = request.json['FileName']
        binaryData = request.json['File'] 

        file_decoded = base64.decodebytes(binaryData.encode('utf-8').strip())

        _file = file_decoded.decode()
        path_to_save = os.path.join(os.getcwd(), 'Watch', filename)
        with open(path_to_save, mode='wb') as f:
            f.write(file_decoded)

        return jsonify({"FileCreated": "Success"})
    except Exception as exc:
        print(f"FileError: {str(exc)}")
        return jsonify( {"Error": f"{str(exc)}"} )

请提前协助和感谢。

【问题讨论】:

  • 您好,导致此错误的行是:file_decoded = base64.decodebytes(binaryData.encode('utf-8').strip())
  • 我不确定python。但是,您是否验证了有效负载的外观是否符合您的预期?
  • 是的,我确实将它显示在我的终端上,使用 request.json['File'] 和 request.json['FileName'] 获取值,另一件事是,如果我删除 base64 编码并解码我确实得到了一个 wav 文件,但它无法播放,所以我认为我的字节已损坏或其他什么,所以我决定使用 base64 字符串将字节发送到我的 API。
  • 但是你从哪里得到错误? file_decoded 是二进制波形文件,因此 _file = file_decoded.decode() 应该会引发错误。只需删除该行。

标签: python utf-8 base64


【解决方案1】:

感谢大家的帮助,但我终于找到了解决方案。 事实证明,我只需要以下行来解码来自我的 C# API 调用的 base64 字符串:

file_decoded = base64.b64decode(binaryData)

再次感谢那些试图提供帮助的人。

【讨论】:

    猜你喜欢
    • 2020-09-22
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    • 2023-02-07
    • 2021-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多