N
N
Nadim Zakirov2021-07-14 10:25:02
JavaScript
Nadim Zakirov, 2021-07-14 10:25:02

How to determine the MIME type of a file by content?

Let's say we have a Blob or File without an explicit type, i.e. the type property is empty.
Is there any easy way to determine the MIME type of a file?
Preferably without the hassle of manually comparing magic numbers !

Test stand for experiments: https://nadim.work/zip/

What I have already tried

У меня была такая идея, попробовать записать файл в виртуальную файловую систему и прочитать его обратно, по моим предположениям операционная система должна автоматически присвоить правильный MIME-тип, но к сожалению это не сработало и MIME-тип так и не присвоился:
window.webkitRequestFileSystem(window.TEMPORARY, 10*1024*1024, function(fs) {
    
    fs.root.getFile(file.name, { create: true }, function (fileEntry) {

        fileEntry.createWriter(function (fileWriter) {

            fileWriter.onwriteend = function(e) {

                console.log('Успех!');

                fs.root.getFile(file.name, {}, function (fileEntry) {

                    fileEntry.file(function (new_file) {
                        console.log('Файл успешно записан и прочитан обратно:');
                        console.dir(new_file);
                    });

                });

            };

            fileWriter.onerror = function(e) {
                console.log('Ошибка:');
                console.dir(e);
            };

            fileWriter.write(file);

        }, function(err) {
            console.log('Ошибка:');
            console.dir(err);
        });

    }, function(err) {
        console.log('Ошибка:');
        console.dir(err);
    });

}, function(err) {
    console.log('Ошибка:');
    console.dir(err)
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Gennady S, 2021-07-20
@gscraft

Hmm, there are two ways to determine MIME: by the file extension, if it is specified correctly, and by its content. If everything is simple with the file extension , then the file will have to be read, trying to check the first bytes with the existing database of format signatures . Surely there are ready-made libraries.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question