Skip to main content
 首页 » 编程设计

python之Base64 解码图像的 Rails API ASCII 转换错误

2024年10月01日7shangdawei

我有一个 Python 脚本,它通过 POST 请求将图像发送到 Rails API。图像是 Base64 编码,然后是 UTF-8 编码。否则请求错误并出现以下错误:

TypeError: Object of type 'bytes' is not JSON serializable 

Python 脚本如下所示:

with open('C:\\Users\\maforlkzus\\Desktop\\test.jpg', 'rb') as f: 
    encoded_image = base64.b64encode(f.read()) 
    image = encoded_image.decode('utf-8') 
payload = { 
    'name': 'testimage', 
    'image': image, 
} 
 
r = requests.post(url, data=json.dumps(payload), headers={'Content-type': 'application/json'}) 

在我的 Rails 应用程序中,我想创建一个保存图像的临时文件。因此我必须对图像进行 base64 解码,但由于 UTF-8 编码,这不起作用。我的 Rails Controller 如下所示:

1 def decode_file 
2   temp_file = Tempfile.new('test') 
3   testfile = self.image.force_encoding('utf-8') 
4   temp_file.write(Base64.decode64(testfile)) 
5   self.file = temp_file 
6 end 
 
>>> Encoding::UndefinedConversionError ("\xFF" from ASCII-8BIT to UTF-8): line 4 in decode_file 

如果我尝试像这样解码它,我会得到同样的错误:

def decode_file 
    temp_file = Tempfile.new('test') 
    temp_file.write(Base64.decode64(self.image)) 
    self.file = temp_file 
end 

我该如何解决这个问题?我是否必须在发送之前对图像进行不同的编码,或者是 API 代码中的问题?

请您参考如下方法:

您可以将编码指定为 BINARY 临时文件使用:

temp_file = Tempfile.new('test', :encoding => 'binary')