24 March, 2011

How to get MIME type on *nix system

If you work with media content, you will likely need to obtain MIME type of files on your hard disk (for example, if your app should be able to send email with attachment).

It's very simple.
First, you need install libmagic devel package on your system (libmagic-dev for Debian-based).
Second, add in your .pro file this line: LIBS += -lmagic
Third, include header: #include <magic.h>
And last, implement this method:

QString getMimeType(const QString &fileName)
{
    QString result("application/octet-stream");
    magic_t magicMimePredictor;
    magicMimePredictor = magic_open(MAGIC_MIME_TYPE); // Open predictor
    if (!magicMimePredictor) {
        qDebug() << "libmagic: Unable to initialize magic library";
    }
    else
    {
        if (magic_load(magicMimePredictor, 0)) { // if not 0 - error
            qDebug() << "libmagic: Can't load magic database - " +
                        QString(magic_error(magicMimePredictor));
            magic_close(magicMimePredictor); // Close predictor
        }
        else
        {
            char *file = fileName.toAscii().data();
            const char *mime;
            mime = magic_file(magicMimePredictor, file); // getting mime-type
            result = QString(mime);
            magic_close(magicMimePredictor); // Close predictor
        }
    }
    qDebug() << "libmagic: result mime type - " + result + "for file: " + 
                fileName;
    return result;
}

For some platforms (such as Fedora) package can have another name: file-libs for library and file-devel for headers.

1 comment: