pythondjangomutagen

mutagen read TemporaryUploadedFile in django


I want to validate my mp3s before saving them to disk, using Mutagen. However with mutagen I can only open a file if it's on disk. Is there a way around this? I would like to be able to do this:

files = request.FILES
mp3 = files.get('mp3')
mp3_audio = MP3(mp3)

Gives me the error:

TypeError: invalid file: <TemporaryUploadedFile: test.mp3 (audio/mpeg)>

Solution

  • A TemporaryUploadedFile file object is already on disk, in a directory reserved for temp files. To analyze it for validity, call a method to get the full path:

    files = request.FILES
    mp3_temp = files.get('mp3')
    mp3_audio = MP3(mp3_temp.temporary_file_path())
    

    see docs at TemporaryUploadedFile.temporary_file_path()