【问题标题】:How to extract the file type from a FileStorage Object如何从 FileStorage 对象中提取文件类型
【发布时间】:2020-05-26 13:26:42
【问题描述】:
print(file) 
>> <FileStorage: 'xyz.pdf' ('application/pdf')>

如何从 FileStorage 对象中提取文件类型(扩展名)?

【问题讨论】:

  • 你能显示你想要的输出吗?
  • 我想在 if 条件中使用文件类型。 if (file_type == ".pdf"): do something

标签: python flask types file-extension file-storage


【解决方案1】:

感谢您的回复。我找到了解决方案。

file.content_type 为您提供 FileStorage 对象的文件类型

【讨论】:

    【解决方案2】:

    这可以通过os.path.splitext 函数来完成,该函数返回文件名和扩展名的元组:

    >>> import os
    >>> os.path.splitext('sample.pdf')
    ('sample', '.pdf')
    

    所以要从 FileStorage 对象中提取扩展名,只需:

    _, ext = os.path.splitext(file.filename)
    

    这也说明了超过 3 个字符的文件扩展名,以及带有多个点的文件名;如果您手动构建一个函数来执行此操作,可能会遗漏一些事情。

    【讨论】:

      猜你喜欢
      • 2017-01-19
      • 2019-03-10
      • 1970-01-01
      • 2021-03-13
      • 2010-10-06
      • 1970-01-01
      • 1970-01-01
      • 2012-08-22
      • 1970-01-01
      相关资源
      最近更新 更多