I have a Python script, that sends an image over a POST-Request to a Rails API. The images is Base64 encoded and then UTF-8 encoded. Otherwise the Request errors with the following error:
TypeError: Object of type 'bytes' is not JSON serializable
The Python script looks like this:
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'})
In my Rails app, I want to create a Temporary File which holds the image. Therefore I have to base64-decode the image, but that does not work because of the UTF-8 encoding. My Rails controller looks like this:
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
If I try to decode it like this, I get the same error:
def decode_file
temp_file = Tempfile.new('test')
temp_file.write(Base64.decode64(self.image))
self.file = temp_file
end
How can I fix this? Do I have to encode the image differently before sending or is the problem in the API code?