【问题标题】:python implementation of 'readAsDataURL'readAsDataURL 的 python 实现
【发布时间】:2011-02-16 18:37:47
【问题描述】:

我在从某个文件(例如 .mp4/.ogg/etc.)获取 URI 时遇到了一些麻烦。 问题是我需要在运行网络服务器的 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

谢谢!

【问题讨论】:

    标签: python uri filereader


    【解决方案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)
    

    【讨论】:

    • 感谢指正!现在看起来很像 readAsDataURL 的结果,但仍然不相等。解析 .mp4 文件时,字符串的开头(结果)具有相同的字符:AAAAHGZ0eXBtcDQyAAAAA....(等等),但它改变了,它们的长度也不同。 728420(python)与 1464184(js)。有什么想法吗?
    • 它正在工作!我不明白为什么会有这种差异,但结果是有效的。我使用给定的 uri 通过视频标签进行了测试,它正在发光。唯一缺少的是第一个 URI 部分,在测试中我已经知道它:data:video/mp4;base64,data。我怎么能找到它?
    • @Nacho -- 我只是使用 mimetypes 库(包含在 Python 中)来猜测文件类型并自己添加 "data:" + mimetype + ";base64," + datadocs.python.org/library/mimetypes.html#mimetypes.guess_type
    • @Nacho -- Huzzah!很高兴我能帮上忙!不要忘记单击0 下方的复选框(如果您认为它特别有用,请单击向上箭头 ["upvote"])。
    • @cheziHoyzer - 明白了! OP 是“我如何将文件的内容编码为 Base64 编码的字符串并确定它是 mime 类型”。这个答案是否遗漏了一些导致这种情况失败的东西,或者您的警告是否与有时file_data 可能非常大并导致内存压力的事实有关? (或者完全有其他问题?)
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-20
      • 1970-01-01
      • 1970-01-01
      • 2014-01-31
      相关资源
      最近更新 更多