Python ';编码数据

Python ';编码数据,python,uri,filereader,Python,Uri,Filereader,我在从某个文件获取URI时遇到了一些问题,如.mp4/.ogg/等。。 问题是我需要在python中完成,Web服务器正在python中运行 最初,我是这样做的: def __parse64(self, path_file): string_file = open(path_file, 'r').readlines() new_string_file = '' for line in string_file: striped_line = line.str

我在从某个文件获取URI时遇到了一些问题,如.mp4/.ogg/等。。 问题是我需要在python中完成,Web服务器正在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)
但是这样,如果你把结果和给定的进行比较,就不会给出我所需要的

我需要的是一种在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? 喜欢

例如:数据:视频/mp4;base64,数据


谢谢

问题在于,您将二进制编码数据视为文本数据,这会破坏您的代码

尝试:


如果文件非常大(超过7mb),则@SeanVieria应答将不起作用

此函数适用于所有情况(在Python 3.4版上测试):


谢谢你的更正!现在它看起来很像readAsDataURL的结果,但仍然不相等。解析.mp4文件时,字符串(结果)的开头具有相同的字符:AAAAHGZ0eXBtcDQyAAAAA…(依此类推),但它会发生变化,并且它们的长度也不同。728420(python)对1464184(js)。有什么想法吗?它在工作!我不明白为什么会有这种差异,但结果是有效的。我通过视频标签运行了一个测试,使用给定的uri,它正在发光。唯一缺少的是第一个URI部分,在测试中我已经知道了:data:video/mp4;base64,数据。我怎么能找到它?@Nacho——我只需要使用mimetypes库(包含在Python中)猜测文件类型,并将
数据:“+mimetype+”;“base64”+data
添加到一起@纳乔,胡萨!很高兴我能帮忙!别忘了单击
0
下面的复选框(如果您认为它特别有用,请单击向上箭头[“向上投票])。@cheziHoyzer-明白!OP是“如何将文件内容编码为Base64编码字符串并确定其mime类型”。此答案是否遗漏了一些不符合该情况的内容,或者您的警告与以下事实有关:有时
文件\u数据可能非常大,并导致内存压力?(或者完全存在其他问题?)
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)
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)