Download a base64 Image data and save into memory

577 views Asked by At

For few days now I am trying to find how the BytesIO is working with what I want to do. So basically I want to download a pdf that its base64 encoded. After downloading it I want to save the file but not on the disk but in memory. And then I need to upload the path of that file to an API. Does anyone know how I could do that?

Until now this is what I have so far.

def string_io_save(document_string: str, attach_id: str, file_name: str, file_type: str):
    img_data = b64decode(document_string)
    path = attach_id
    out_stream = BytesIO()
    with open('imageToSave.pdf', 'wb') as f:
        f.write(img_data)
        bytesio = BytesIO(f.read())
    return bytesio
1

There are 1 answers

2
Iñigo González On

You can create a file-like BytesIO like this: BytesIO(img_data)

Your function this way is much simpler:

def string_io_save(document_string: str):
   img_data = b64decode(document_string)
   return BytesIO(img_data) 

now you can work with the return value of string_io_save as if it were a regular file (which is very useful for testing purposes):

fp = string_io_save("base64-encoded-sting....")
foo = fp.read()
fp.close()