string formatted as base64 to base64 object - python

From a post request, I receive a base64 in JSON. Problem is that I can't just change the file type from string to base64 since it's already formatted as base64. need the base64 to convert it back to an image.
json_data = request.get_json(force=True)
img = json_data['img']
print(img)
with open("imageToSave.png", "wb") as fh:
fh.write(base64.decodebytes(img))

In order to decode it, add the third line which decodes the string to base64
json_data = request.get_json(force=True)
img = json_data['img']
imgdata = base64.b64decode(img)
filename = 'upload/newimg.jpg' # I assume you have a way of picking unique filenames
with open(filename, 'wb') as f:
f.write(imgdata)

Related

Convert zip file to bytes in python

Goal for question - open a zip file and convert it into a bytes-like object.
When I tried I get the error:
encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'list'
Here is the code:
import base64
with open("results.zip", 'rb') as f:
data = f.readlines()
print(data)
encoded = base64.b64encode(data)
I also tried this and got the same exact error:
import zipfile
with open("results.zip", 'rb') as f:
data = f.readlines()
zf = zipfile.ZipFile(io.BytesIO(data), "r")
for fileinfo in zf.infolist():
print(zf.read(fileinfo).decode('ascii'))
Thanks to #Vlad for his comment as it helped me to get the answer.
import base64
with open("results.zip", 'rb') as f:
data = f.read()
print(data)
encoded = base64.b64encode(data)

Handling a Txt file content as a String Variable

I have a json file, and I need to read all of that json file content as String data. How can I read all the data and set a variable as a String for all of that content? Json file has blanks, new lines, special characters etc if it's neccesarry.
Thanks for your help!
import json
from ast import literal_eval
with open('<path_to_json_data>/json_data.txt') as f:
json_data = json.load(f) # dict object
print(json_data, type(json_data))
json_data_as_str = str(json_data) # dict-->str object
print(json_data_as_str, type(json_data_as_str))
data = literal_eval(json_data_as_str) # str-->dict object again
print(data, type(data))
Hope it helps
Simple as this example
import json
with open("path/to/json/filename.json", "r") as json_file:
data = json.load(json_file)
print(data)
dataStr = json.dumps(data)
print(dataStr)
use json.loads
import json
with open(file_name, "r") as fp:
as_string = str(json.loads(fp.read()))

How to convert a Base64 file to bytes?

I am trying to pass a base64 to bytes. But I think I'm doing it wrong because I'm passing it to ascii. The file is much bigger but I didn't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V2SF9t/sF1LNy+18+fnp6+3j60pEE9GHzgia2NDXR0UzzEoja9Oni33Vfn9XW0L5qtMaHT6vstoVPVOtm0mqo42qo81ra8Uo+scwfN/Uy43eFq1mcN1d9FMFKXAVet0DuFvl7Uffwj9++7vZZvan3KWUkK3A+qOMgCE8iuBNrr4EuBLm+kVzD83t4CSpIGoB+Ho55pTEYlgdNSgLaI1hiir8yfzQV1jSFpkKeBfRSF3qwxal+N/lrJMvLRII30vw9vFQrzZpsmJUhdixlSdIK+wpCjMsHTsIqtvIOyrIRqI2EsObBLkiqmcd/zYwJrcmmx2I/SOMF7izpVh6v0ej5t7eodw3vUSS3+BuqhlL4RCgij9pSVVtB5CRSFuxtZyXwNpvJUemI5WsUP+p2aOCYR8C51Vl7XY/bj/vy+8la+jltcL+sLq66hiezb88Y7QujOqIs+IXSaOJLNOG1y2+jT+MaFIxh48GuSJbpNxseLiuL2+nkC7dEtI4O48Ir59txDBZYvwa/dGvmlAzF6fIE7EviVdZQNCybdIM+/AZ5HfaeIuYLaDyxeaN1K29ozI2dC7MFe95QWMFFr8r+5eOYl8QuOQQb3xS1LKxhkZGaadWPX4ZzMESLiWlE+9JeeMSpeRmYmhdr3rFOI607e9PRgZJajKmaCt/plY0O46JgzDPeEgZYkyckfysIhRG8KhoKlyIdWltWKto1yXuNP4O0NURWuV9o9kuk4h4jlMVvrMq3nXVuWNsWotMYnZ8wcoY8mh+C4IwtvwNtGQkYzVpIxJ1l10XxHEb2i0e7IrbIQ+zWEhZGFx1TZ/EXdvnV/dwMcA1Q24uFGWKrZ6xOOH8Bz2xgwNpk4WiEzdMvioOAN0KcBKb5pc0bi4='
base64_bytes = base64_message.encode('ascii')
message_bytes = base64.b64decode(base64_bytes)
message = message_bytes.decode('ascii')
print(message)
you can find the following here:
import base64
base64_message = 'UHl0aG9uIGlzIGZ1bg=='
base64_bytes = base64_message.encode('ascii')
message_bytes = base64.b64decode(base64_bytes)
message = message_bytes.decode('ascii')
print(message)
Source: https://stackabuse.com/encoding-and-decoding-base64-strings-in-python/
just two line could solve this problem:
import base64
base64_code = "VER30QHI30JFOIAIO3020085723F" # this is just a example
img_data = base64_code.encode()
content = base64.b64decode(img_data)
with open('/path/to/your/image.jpg', 'wb') as fw:
fw.write(content)
print(content)
then you could check the image bytes.

How to convert base64 encoded string to file without disk I/O in Python (for HTTP requests)

I want to send a file through requests library in Python, it accepts file type input. Here is a piece of working code I've tested myself.
FILES = []
f = open('/home/dummy.txt', 'rb')
# f : <type 'file'>
FILES.append(('file', f))
response = requests.post(url = 'https://dummy.com/dummy', headers = {'some_header':'content'}, data={'some_payload':'content'}, files=FILES)
This works just fine, now I have a base64 encoded string I just got from my database
base64_string = "Q3VyaW91cywgYXJlbid0IHlvdT8="
FILES = []
f = convert_base64_to_file(base64_string, "dummy.txt")
# f : <type 'file'>
FILES.append(('file', f))
response = requests.post(url = 'https://dummy.com/dummy', headers = {'some_header':'content'}, data={'some_payload':'content'}, files=FILES)
I need the convert_base64_to_file (which is an imaginary method). How do I achieve this without any disk I/O?
My base64_string doesn't have a filename. How do I simulate the filename so that it behaves just like I open a file from my disk?
I need the http request to post this:
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file"; filename="dummy.txt"
Content-Type: application/x-object
... contents of file goes here ...
That's why I need to specify the filename.
You can use the io module:
import io
FILES = {}
f = io.BytesIO()
FILES{'file'] = ("dummy.txt", f)
response = requests.post(url = 'https://dummy.com/dummy', headers = {'some_header':'content'}, data={'some_payload':'content'}, files=FILES)
Here is the convert_base64_to_file function:
import base64
import io
def convert_base64_to_file(data):
return io.BytesIO(base64.b64decode(data))
To complete Megalng answer which solves half of my problem, we can add a name to the constructed file by doing this:
import base64
import io
def convert_base64_to_file(base64_string,filename):
f = io.BytesIO(base64.b64decode(base64_string))
f.name = filename
return f

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

Categories