Python实现'readAsDataURL

4 投票
2 回答
1406 浏览
提问于 2025-04-16 11:57

我在获取某个文件的URI时遇到了一些麻烦,比如.mp4、.ogg等格式的文件。问题是我需要在运行着网络服务器的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呢?就像这样

举个例子:data:video/mp4;base64,data

谢谢!

2 个回答

0

如果文件非常大(超过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)
1

问题在于你把二进制编码的数据当成文本数据来处理,这样会导致你的代码出错。

你可以试试:

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)

撰写回答