2010-02-09 93 views
72

有沒有辦法找到一個Linux bash腳本中的文件的MIME類型(或稱爲「Content-Type」...)?如何找出文件「mime-type(Content-Type?)」?

我之所以需要它是因爲ImageShack的似乎需要它來上傳文件由於某種原因,檢測.png文件作爲一個「應用程序/八位字節流」 ......

心中已經檢查的文件,它確實是一個巴紐

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

這給我的錯誤:

$ curl -F "[email protected]/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> 

這工作,但我需要指定一個MIME類型。

$ curl -F "[email protected]/1.png;type=image/png" http://www.imageshack.us/upload_api.php 

回答

143

使用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 
+0

乾杯,「文件--mime-type /1.png」很好用! – Mint 2010-02-09 06:32:19

+0

如果您在Windows下使用Git bash,請不要使用它。 – tivo 2011-09-23 08:25:06

+1

只需**就可以執行mime類型:'file --mime-type FILE_NAME | awk'{print $ 2}'' – 2012-08-23 00:30:40

16

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

xdg-mime query filetype query filetype <file>

如果你有蔭,

yum install xdg-utils.noarch

一個例子比較xdg-mime和Subrip(字幕)文件上的文件

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

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

在上述文件中只顯示爲純文本。

+0

xdg-mime查詢filetype install.sql; xprop:無法打開顯示'' – 2012-10-09 12:42:06

+0

xdg-mime是一個bash腳本,很大程度上依賴於環境變量。其中一些例如如果您未登錄會話,則DE未設置。親自檢查一下'$ less $(which xdg-mime)' – ManuelSchneid3r 2014-09-08 23:32:34

1

嘗試file命令與-i選項。

-i選項使文件命令輸出MIME類型字符串,而不是更傳統的可讀的字符串。因此可以說text/plain; charset=us-ascii而不是ASCII text

1

file --mime有效,但不是--mime-type。至少對於我的RHEL 5.

+0

這也適用於Linux Mint 12 – 2012-10-09 12:40:52

7

文件版本< 5:文件-i -b /路徑/到/文件
文件版本> = 5:文件--mime型-b /路徑/到/文件