Check if file format is different with filename extension in Python, Javascript?

I have a file format checker downloader (only some video formats can be uploaded).

However, users can simply change the original file name extension and pass a confirmation (like rename file.pdf

to file.mov

and download)!

Now I need to check and check if the file format matches the file extension or not. The backend is Python (Django), but I'm not sure if this can be done with Payton, Javascript, or any other solution.

+3


source to share


3 answers


In python, you can use python-magic

Quoting from the Readme:

python-magic is a python interface to the libmagic file type identification library. libmagic identifies file types by checking their headers according to a predefined list of file types.



It parses the file header instead of just using the file extension to recognize the file type.

Usage is simple:

>>> import magic
>>> magic.from_file('renamed.pdf')
'ISO Media, Apple QuickTime movie'
# More handy
>>> magic.from_file('renamed.pdf', mime=True)
'video/quicktime'

      

+8


source


If you want to do it with Javascript, you can get the mime type of the selected file and validate in the frontend. The advantage of this is that you do not need to upload the file to the server for initial verification. Based on this , the mime type for .mov files is video / quicktime. It is very difficult for the user to change rather than change the file extension.

Also note the answer by Matthias . It's also important to check the uploaded file on the backend server. :)



Below is a demo of validating a file using Javascript .

$('#movieFile').change(function() {
    var file = $('#movieFile')[0].files[0];

    var filename = file.name;
    var fileMimeType = file.type;
    var fileExtension = filename.split('.').pop();

    if (isValidMimeType(fileMimeType)) {
        console.log('good file');
    } else {
        console.log('bad file');
    }
});

function isValidMimeType(fileMimeType) {
    // mime type of .mov files
    var validFileMimeTypes = [ 'video/quicktime' ];

    for (var i = 0; i < validFileMimeTypes.length; i++) {
        if (validFileMimeTypes[i].toLowerCase() === fileMimeType.toLowerCase()) {
            return true;
        }
    }
    return false;
}

      

+3


source


adding on Matthias answer using python magic you could do this instead

file_type = magic.from_buffer(upload.file.read(1024), mime=True)

      

it won't require saving the file to get its mime

-1


source







All Articles