Error base64 encoding when testing upload image in django restful framework

Viewed 250

I'm writing unit tests trying to upload images and base64 encode it. But the encoding is different from expected.

This is my tests.py

    with open('tests/image.jpg', 'rb') as image:
        r = self.client.post('/images', {'image': image}, format='multipart')

This is my views.py

def post(self, request):
    image = request.FILES['image']
    base64_str = base64.b64encode(image.read()).decode('utf-8')

The base64_str turns out to be like 7f7NCd0Aw29mVx......

Doing in a python script

with open('tests/image.jpg', 'rb') as f:
    print(base64.b64encode(f.read()).decode('utf-8'))

The output is /9j/4AAQSk......

I suppose there is something wrong with the encoding. So what's the problem?

1 Answers

You sure you didn't just use encode, instead of decode in base64.b64encode? After you encode you can decode with b64decode I think it should be:

with open('tests/image.jpg', 'rb') as f:
     encoded_photo = base64.b64encode(f.read()).decode('utf-8'))
     decoded_photo = base64.b64decode(f.read()).decode('utf-8'))
Related