Изменить mime type файла linux

How do you change the MIME type of a file from the terminal?

The result would be that filename.pdf would then be typed as application/pdf. The reason for the question is that sometimes web servers use the wrong MIME type, which results in programs refusing to open the file. (Most often text/plain, in my experience.) I’ve been searching man , the web and this site for about two and a half hours. Tried everything from hex dumps to xattr to text editors. Your help would very much be appreciated. Chris

I’m using OS X. I mentioned Linux because there was a spat elsewhere on this site about -I vs -i, respectively. Both therefore seemed relevant, though.

3 Answers 3

The thing about MIME types is they’re almost entirely fictional.

MIME and HTTP ask us to pretend that all of our files have a piece of metadata identifying the «content type». When we send files around the network, the «content type» metadata goes with them, so nobody ever misinterprets the content of a file.

The truth is this metadata doesn’t exist. By the time MIME was invented, it was really too late to convince any OS vendors to adopt a new type system for files. Unix had settled on magic numbers, DOS had settled on 3-letter filename suffixes, and classic MacOS had its creator codes and type codes. (MacOS type codes were closest to the MIME model, since they actually were separate from both the filename and the content. But being only 4 letters long, MIME types wouldn’t fit.)

Nobody stores MIME-compatible content types in their filesystem. When a MIME message composer or HTTP server wants to send a file, it decides the file type in the traditional way (filename suffix and/or magic number) and maps the result to a MIME type.

In contrast to the theory (where MIME eliminates file type guessing), MIME as implemented in practice has moved the «guess file type based on filename suffix and/or magic number» logic from the receiver of the file to the sender. As you have noticed, the sender doesn’t usually do a better job than the receiver would have done if forced to figure it out for itself. Frequently in the case of a web server, the server’s eagerness to slap a Content-type on a file makes things worse. There’s no reason for a web server to know anything about the format of files it serves when it is only being used to distribute them and has no need to interpret their contents.

The file command guesses file type by reading the content and looking for magic numbers and strings. The -I option doesn’t change that. It just chooses a different output format.

To change the Content-Type header that a web server sends for a specific file, you should be looking in your web server’s configuration manual. There’s nothing you can do to the file itself.

Classic Mac OS type and creator codes are not stored in the resource fork, but in fields of the disk catalog. (Not that it’s important for this question.)

Читайте также:  Изображения в pdf linux

Thank you for the explanation. It’s funny because I suspected a few things you just confirmed. (Although, you added considerably more after that!) Two things if I may. First, OS X does store MIME types of downloaded files, but I don’t see that it uses the information for any practical purpose. If you drop such a file into Text Wrangler, for example, the binary is surrounded by XML tags, one of which is MIME type. Changing it does not change file -I output or solve any problems. Second, so, when I d/l a pdf that opens as a text file and changing the .ext doesn’t work, how do I fix it?

This is a matter of cost. Server running the HTTP service is assumed to be in better position to perform the magic because it’s closer to the file, it’s assumed to be more powerful than client computers, and can cache that information for future use.

It’s worth noting that binary cloud storage (Amazon S3, Azure Blob Storage, etc.) nowadays DOES store separate metadata for each binary including Content-Type . Whatever the uploading client passed as mime type in the Content-Type header will be stored there and returned when reading the resource using GET or HEAD requests.

It’s a bit of a category mistake to talk about ‘the MIME type of a file’ – ‘files’ don’t have MIME types; only octet streams have them (I’m not necessarily disagreeing with @wumpus-q-wumbley’s description of MIME types as ‘fictional’, but this is another way of thinking about it).

MIME stands for Multipurpose Internet Mail Extensions, as originally described in in RFC 2045, and MIME types were originally intended to describe what a receiver is supposed to do with the bunch of bytes soon to follow down the wire, in the rest of the email message. They were very naturally repurposed in (for example) the HTTP protocol, to let a client understand how it is to interpret the bytes in the HTTP response which this MIME type forms the header of.

The fact that the file command can display a MIME type suggests the further extension of the idea, to act as the key which lets a windowing system look up the name of an application which should be used to open the file.

Thus, if ‘the MIME type of a file’ means anything, it means ‘the MIME type which a web server would prefix to this file if it were to be delivered in response to an HTTP request’ (or something like that). Thought of like that, it’s clear that the MIME type is part of the web server’s configuration, and not anything intrinsic to the file – a single file might be delivered with various MIME types depending on the URL which retrieves it, and details of the request and configuration. Thus an XHTML file might be delivered as text/html or application/xml or application/octet-stream depending on the details of the HTTP request, the directory the file’s located in, or indeed the phase of the moon (the latter would be an unhelpful server configuration).

A web server might have a number of mechanisms for deciding on this MIME type, which might include a lookup table based on any file extension, a .htaccess file, or indeed the output of the file command.

Читайте также:  Linux версия системы debian

So the answer to your question is: it depends.

  • If what you want to do is change how a web server delivers this file, then you need to look at either your web server documentation, or the contents of your system’s /etc/mime.types file (if your system uses that and if the server is configured to fall back on that).
  • If what you want to do is to change the application which opens a given (type of) file, then your OS/window-manager documentation should help.
  • If you need to change the output of the file command specifically, for some other reason, then man file is your friend, and you’ll probably need to grub around in the magic numbers file, reasonably carefully.

Источник

AddingMimeTypes

MIME types are a sort of identification card for files on Ubuntu. A file’s MIME type is usually determined by the extension of its filename; for example, a text file may end in .txt, and image file might end in .png or .jpg. This tells Ubuntu what icon should be used to represent it and what programs should open it by default.

Unfortunately, the obvious options for editing MIME types in Ubuntu are shallow. You can teach Ubuntu to open a certain file extension with a certain program using the Properties window, but you cannot set an icon for that extension as a whole: only for the individual file. This can be annoying if you are say, a Python programmer. Ubuntu does not include a special icon for Python files, and it is hard to visually differentiate .py and .pyc files.

This guide will both teach you to add new MIME types and to associate icons with existing types. We will use .py files as an example.

Adding a MIME Type

To start out, we must be assure that the MIME type for our file extension does not already exist. Open a command line and enter the line below, replacing the letters py with your extension.

Analysing results

This particular command will output two lines. If your extension does not output any lines, or if the lines outputed do not include your extension, you must create a new MIME type. Otherwise, look at the right side of this output, find your file extension, and copy the corresponding text to the far right. For ‘py’, we must copy down ‘text/x-python’.

application/x-python-code pyc pyo text/x-python py

Creating the MIME type, if needed

If there was no output, or the output given did not include your extension, we must add a MIME type.

gksudo gedit /etc/mime.types

Modify the following text so that the word «extension» is replaced with your file extension (no period mark), add the line to the end of the mime.types file, and save.

And copy the modified ‘text/extension’ part.

Another way to add a MIME Type

On 12.04LTS, I edited the /etc/mime.types file and it had no effect. What worked for me was to add xml files in /usr/share/mime/application; for example here’s a file (scad.xml) to describe scad files:

After you’ve added or modified whatever you need, run the command

sudo update-mime-database /usr/share/mime

Adding an Icon

Now we need to associate an icon with the MIME type. Get an SVG icon and name it «text-extension.svg», or whatever your modified MIME type is named; this will be the icon to represent all instances of the MIME type on your system. For our python example, this is a good choice. Rename the .svg file so that the it matches «text-x-python.svg» (or «insertYourMIMEtype.svg») so that the slashes are replaced with «-» and there are no capital letters.

Читайте также:  Linux run command ssh

Then simply run the following commands, with ‘text-x-python’ replaced with your MIME type.

sudo cp text-x-python.svg /usr/share/icons/gnome/scalable/mimetypes sudo gtk-update-icon-cache /usr/share/icons/gnome/ -f

Relogin and all files ending in the MIME extension will display with that icon.

AddingMimeTypes (последним исправлял пользователь rrcs-24-103-168-22 2014-02-03 21:59:21)

The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details

Источник

Как назначить (установить) тип MIME для файла?

Есть ли команда, которая может установить MIME-тип файла? например:

mime --set --MIME="image/pjpeg" filename.jpg 

2 ответа

Вопрос уже ответил @PHPLearner в своем комментарии сам. Однако, ради Ответа, Здесь Это идет.

Там нет конкретной команды как таковой mime как задано в вопросе, и, без сомнения, одна такая команда может быть создана. Для добавления нового типа MIME достаточно всего лишь отредактировать /etc/mime.types файл.

Допустим, вы хотите добавить MIME-тип с расширением .btc , затем

1. Проверьте, существует ли тип MIME

Откройте командную строку и введите строку ниже. (заменить btc с твоим расширением)

Теперь эта команда выведет строку, если этот тип MIME уже добавлен. Похоже, это для конкретных поисков MIME

$ grep 'cpp' /etc/mime.types text/x-c++src c++ cpp cxx cc $ grep 'py' /etc/mime.types application/x-python-code pyc pyo text/vnd.debian.copyright text/x-python py $ grep 'btc' /etc/mime.types 

Если ваше расширение не выводит никаких строк (как для btc в этом случае), или если в выдаваемых строках нет вашего расширения, вы должны создать новый тип MIME. В противном случае ваше расширение уже имеет тип MIME, включенный в файл /etc/mime.types.

2.1 Создание типа MIME (если требуется)

Если выходных данных не было или данные не содержали вашего расширения, мы должны добавить тип MIME. Для этого типа в командной строке

Измените следующий текст, чтобы слово «расширение» заменялось расширением вашего файла. (no period mark) , добавьте строку в конец файла mime.types и сохраните. Здесь наше расширение — биткойн, и мы пишем btc (NOT .btc) это будет рассматриваться как расширение для файлов биткойнов.

И скопируйте измененную часть «текст / расширение».

В нашем случае это будет выглядеть так

2.2 Добавление MIME-типа с помощью .xml файл и update-mime-database

Если редактирование /etc/mime.types файл не работает для вашего расширения, тогда вы можете попробовать этот обходной путь.

Создать новый .xml файл, который описывает ваше расширение, как это и сохранить его.

Теперь добавьте этот файл в /usr/share/mime/application Папка. После того, как вы добавили или изменили все, что вам нужно, выполните команду

$ sudo update-mime-database / usr / share / mime

3. Добавление иконки в MIME-тип

Теперь нам нужно связать значок с типом MIME. Получите значок SVG и назовите его «text-extension.svg», или как бы вы ни назвали ваш измененный тип MIME; это будет значок для представления всех экземпляров типа MIME в вашей системе.

Итак, мы переименовываем файл.svg, чтобы он соответствовал bitcoin-text.svg (или «insertYourMIMEtype.svg»), чтобы slashes are replaced with «-» и здесь no capital letters ,

Затем просто выполните следующие команды, заменив «биткойн-текст» на ваш тип MIME.

$ sudo cp bitcoin-text.svg /usr/share/icons/gnome/scalable/mimetypes $ sudo gtk-update-icon-cache /usr/share/icons/gnome/ -f 

Relogin и все файлы, заканчивающиеся расширением MIME, будут отображаться с этим значком.

Источник

Оцените статью
Adblock
detector