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

mfa*_*zus 5 python base64 encoding ruby-on-rails utf-8

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

TypeError: Object of type 'bytes' is not JSON serializable
Run Code Online (Sandbox Code Playgroud)

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'})
Run Code Online (Sandbox Code Playgroud)

在我的 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
Run Code Online (Sandbox Code Playgroud)

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

def decode_file
    temp_file = Tempfile.new('test')
    temp_file.write(Base64.decode64(self.image))
    self.file = temp_file
end
Run Code Online (Sandbox Code Playgroud)

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

geo*_*xsh 5

您可以指定 Tempfile 使用的编码BINARY

temp_file = Tempfile.new('test', :encoding => 'binary')
Run Code Online (Sandbox Code Playgroud)