我有一些麻烦从某个文件中获取URI,比如.mp4 / .ogg / etc。事情是我需要在运行webserver的python中进行。
最初,我这样做:
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)
但是这样,如果你把结果与给定的here.进行比较,就没有给出我需要的东西
我需要的是一种在python中实现FileReader类中的函数readAsDataURL()的方法(参见上面链接的代码)。
更新:@SeanVieira给出的解决方案返回URI的有效数据字段。
def __parse64(self, path_file):
file_data = open(path_file, 'rb').read(-1)
self.encoded_string_file = b64.b64encode(file_data)
现在我如何使用之前的字段填写URI?像this。
例如:data:video / mp4; base64,data
谢谢!
问题是您将二进制编码的数据视为文本数据,这会破坏您的代码。
尝试:
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)
如果文件非常大(超过7mb),则@SeanVieria答案将不起作用
此函数适用于所有情况(在Python 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)