如何区分zip档案中的xlsx和docx文件? [英] How to distinguish xlsx and docx files from zip archives?

查看:459
本文介绍了如何区分zip档案中的xlsx和docx文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用例,我需要知道文件的文件类型,以识别可执行文件(exe,安装程序等)和存档文件(zip,rar等)并将其列入黑名单.因此,依靠扩展名对我来说还不够,因为可以更改文件的扩展名,但文件属性将保持不变.我尝试使用linux命令:

I have a use case where I need to know the file type of a file to identify and blacklist the executables(exe,installers etc), archive files(zip, rar etc.). Therefore relying on the extension is not enough for me as the extension of a file can be changed but the file property will remain the same. I tried using the linux command:

file --b filename

上述解决方案可以与.xlsx和.docx文件以外的所有文件类型完美配合,因为该命令为.xlsx和.docx提供了以下内容

The above solution is working perfectly with all the file types except the .xlsx and .docx file because the command is giving the following for the .xlsx and .docx

压缩存档数据,至少要提取v2.0

Zip archive data, at least v2.0 to extract

因此,我最终也将.xlsx和.docx文件列入黑名单.

And because of this I end up blacklisting the .xlsx and .docx file as well.

有人可以建议我一种无需使用适用于xlsx和docx的扩展名的文件类型的方法.

Can anybody suggest me a way to get the file type without using the extension that works for the xlsx and docx as well.

推荐答案

我使用了 Mimemagic Gem 和添加了自定义魔术(如宝石所称)来标识xlsx,docx和pptx文件格式.同样,这不依赖于文件扩展名.

I used Mimemagic Gem and added custom magic(as it is called by the Gem) to identify xlsx, docx, and pptx file format. Also this does not relies on the file extension.

以下是我添加的魔法列表:

Following are the list of magic that I added:

[['application/vnd.openxmlformats-officedocument.wordprocessingml.document.custom', [[0, "PK\x03\x04", [[30, '_rels/.rels', [[0..5000, 'word/']]]]]]],
['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.custom', [[0, "PK\003\004", [[30, '_rels/.rels', [[0..5000, 'xl/']]]]]]],
['application/vnd.openxmlformats-officedocument.presentationml.presentation.custom', [[0, "PK\003\004", [[30, '_rels/.rels', [[0..5000, 'ppt/']]]]]]],['application/vnd.openxmlformats-officedocument.wordprocessingml.document.custom', [[0, "PK\x03\x04", [[30, 'word/']]]]],
['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.custom', [[0, "PK\003\004", [[30, 'xl/']]]]],
['application/vnd.openxmlformats-officedocument.presentationml.presentation.custom', [[0, "PK\003\004", [[30, 'ppt/']]]]]].each do |magic|
  MimeMagic.add(magic[0], magic: magic[1])
end

这篇关于如何区分zip档案中的xlsx和docx文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆