Rails API ASCII 转换错误与 Base64 解码图像



我有一个Python脚本,它通过POST-Request将图像发送到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 控制器如下所示:

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 Tempfile 使用:

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

最新更新