简体   繁体   中英

Prepend information in base64 encoding

Here is an answer which gives some information on how to base64 encode a file. However, I also want to pass in the filetype and mimetype. for the information in the base64 encoded string.

So far I have for my base64 string:

x=base64.b64encode(open('/Users/user/Desktop/img.PNG').read())

What is the correct information to prepend, and how would I do this?

It seems like the following is how I would get the base64 file information to pass to the server:

file = '/Users/user/Desktop/img.PNG'
prepend_info = 'data:%s;base64' % mimetypes.guess_type(file)[0]
base_64_data = open(file).read().encode('base64')
image_data_base64 = '%s,%s' % (prepend_info, base_64_data)

This then gives me:

data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wB...

Perhaps something along these lines:

from __future__ import print_function
import base64
import binascii
import os

def base64_encode_file(filename):
    filetype = os.path.splitext(filename)[1][1:]  # remove leading '.' from ext
    with open(filename) as file:
        data = file.read()
        return base64.b64encode(','.join((filename, filetype, data))), data

filename = 'C:/Users/martin/Desktop/img.PNG'
#filename = '/Users/user/Desktop/img.PNG'

encoded, data = base64_encode_file(filename)
print('encoded: {} (hex file data: {})'.format(encoded, binascii.hexlify(data)))

decoded = base64.b64decode(encoded).split(',', 2)
print('decoded:', decoded[0], decoded[1], binascii.hexlify(decoded[2]))

Output:

encoded: QzovVXNlcnMvbWFydGluL0Rlc2t0b3AvaW1nLlBORyxQTkcsiVBORwo= 
          (hex file data: 89504e470a)
decoded: C:/Users/martin/Desktop/img.PNG PNG 89504e470a

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM