python implementation of 'readAsDataURL
i'm having some troubles to get the URI from a certain file, like .mp4/.ogg/etc.. The thing is that i need to do it in python, where the webserver is running.
Initially, i proceed like this:
def __parse64(self, path_file):
string_file = open(path_file, 'r').readlines()
new_string_file = ''
for line in string_file:
striped_line = line.strip()
separated_lines = striped_line.split('\n')
new_line = ''
for l in separated_lines:
new_line += l
new_string_file += new_line
self.encoded_string_file = b64.b64encode(new_string_file)
But this way, doesn't give what i need, if you compare the result with given here.
What a i need is a 开发者_运维知识库way to implement the function readAsDataURL() from FileReader class (see the code of the link above), in python.
UPDATE: The solution given by @SeanVieira, returns a valid data field for the URI.
def __parse64(self, path_file):
file_data = open(path_file, 'rb').read(-1)
self.encoded_string_file = b64.b64encode(file_data)
Now how can i complete the URI, with the previous fields? Like this.
For example: data:video/mp4;base64,data
Thanks!
The problem is that you are treating binary-encoded data as text data, which is breaking your code.
Try:
def __parse64(self, path_file):
file_data = open(path_file, 'rb').read(-1)
#This slurps the whole file as binary.
self.encoded_string_file = b64.b64encode(file_data)
The @SeanVieria answer will not work if the file is very large (more than 7mb)
This function will work for all cases (tested on Python version 3.4):
def __parse64(self, path_file):
data = bytearray()
with open(path_file, "rb") as f:
b = f.read(1)
while b != b"":
data.append(int.from_bytes(b, byteorder='big'))
b = f.read(1)
self.encoded_string_file = base64.b64encode(data)
精彩评论