Python Base64解码图像的Rails API ASCII转换错误
我有一个Python脚本,它通过POST请求将图像发送到Rails API。图像是Base64编码,然后是UTF-8编码。否则,请求将出错,并出现以下错误:Python Base64解码图像的Rails API ASCII转换错误,python,ruby-on-rails,encoding,utf-8,base64,Python,Ruby On Rails,Encoding,Utf 8,Base64,我有一个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.b64e
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'})
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
在我的Rails应用程序中,我想创建一个保存图像的临时文件。因此,我必须对图像进行base64解码,但由于UTF-8编码,这不起作用。我的Rails控制器如下所示:
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'})
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')
谢谢,这不起作用,但它给了我一个解决问题的好提示。这是我的新代码:
decoded_data=Base64.decode64(self.image)temp_file=Tempfile.new('test')file.open(temp_file,'wb'){f | f.write(Base64.decode64(self.image).force_encoding('utf-8')}
很好,:encoding=>'binary'
对我来说很有用,不过我对ruby不太熟悉。是的尝试和错误,但再次感谢您的提示。:)