Linux 如何找出文件的 MIME 类型(Content-Type)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2227182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 19:45:39  来源:igfitidea点击:

How can I find out a file's MIME type (Content-Type)?

linuxbashcontent-typemimemime-types

提问by Mint

Is there a way to find out the MIME type (or is it called "Content-Type"?) of a file in a Linux bash script?

有没有办法在 Linux bash 脚本中找出文件的 MIME 类型(或者称为“内容类型”?)?

The reason I need it is because ImageShack appears to need it to upload a file, as for some reason it detects the .png file as an application/octet-streamfile.

我需要它的原因是 ImageShack 似乎需要它来上传文件,因为出于某种原因它将 .png 文件检测为application/octet-stream文件。

I've checked the file, and it really is a PNG image:

我检查了文件,它确实是一个 PNG 图像:

$ cat /1.png 
?PNG
(with a heap load of random characters)

This gives me the error:

这给了我错误:

$ curl -F "fileupload=@/1.png" http://www.imageshack.us/upload_api.php
<links>
<error id="wrong_file_type">Wrong file type detected for file 1.png:application/octet-stream</error>
</links>

This works, but I need to specify a MIME-TYPE.

这有效,但我需要指定一个 MIME-TYPE。

$ curl -F "fileupload=@/1.png;type=image/png" http://www.imageshack.us/upload_api.php

采纳答案by bhups

Use file. Examples:

使用file. 例子:

> file --mime-type image.png
image.png: image/png

> file -b --mime-type image.png
image/png

> file -i FILE_NAME
image.png: image/png; charset=binary

回答by ghostdog74

one of the other tool (besides file) you can use is xdg-mime

您可以使用的其他工具(除了文件)之一是 xdg-mime

eg xdg-mime query filetype <file>

例如 xdg-mime query filetype <file>

if you have yum,

如果你有百胜,

yum install xdg-utils.noarch

yum install xdg-utils.noarch

An example comparison of xdg-mime and file on a Subrip(subtitles) file

一个 Subrip(subtitles) 文件上 xdg-mime 和文件的比较示例

$ xdg-mime query filetype subtitles.srt
application/x-subrip

$ file --mime-type subtitles.srt
subtitles.srt: text/plain

in the above file only show it as plain text.

在上面的文件中只显示为纯文本。

回答by codaddict

Try the filecommand with -ioption.

尝试file带有-i选项的命令。

-ioption Causes the file command to output mime type strings rather than the more traditional human readable ones. Thus it may say text/plain; charset=us-asciirather than ASCII text.

-ioption 使 file 命令输出 mime 类型的字符串,而不是更传统的人类可读的字符串。因此它可以说text/plain; charset=us-ascii而不是ASCII text

回答by fanchyna

file --mime works, but not --mime-type. at least for my RHEL 5.

file --mime 有效,但 --mime-type 无效。至少对于我的 RHEL 5。

回答by Andrey

file version < 5 :file -i -b /path/to/file
file version >=5 :file --mime-type -b /path/to/file

文件版本 < 5 :file -i -b /path/to/file
文件版本 >=5 :file --mime-type -b /path/to/file