Home > Back-end >  Get MIME type of file that is in memory - Python Django
Get MIME type of file that is in memory - Python Django

Time:12-16

I have a form where users can upload files. I only want them to be able to upload images. I have added that in the HTML form but need to do a server side check. I would like to do this check before I save the file to AWS S3.

Currently I have this:

from .models import cropSession, cropSessionPhoto

import magic

def crop(request):
    if request.method == 'POST':
        data = request.POST
        images = request.FILES.getlist('photos')
        crop_style = data['style']

        if len(images) <= 0:
            messages.error(request, "At least one photo must be uploaded.")
            return redirect(reverse('crop-form'))

        crop_session = cropSession(crop_style=crop_style)
        crop_session.save()
        for image in images:
            mime = magic.Magic(mime=True)
            mime.from_file(image.file)
            upload = cropSessionPhoto(crop_session=crop_session, photo_file_name=image, photo_file_location=image)
            upload.save()

    else:
        messages.error(request, "An error has occured.")
        return redirect(reverse('crop-form'))

    return render(request, 'crop/crop.html')

However, I get this error: TypeError: expected str, bytes or os.PathLike object, not BytesIO

How do I properly pass the image to magic?

Thank you

CodePudding user response:

Magic expects the argument for from_file to be a path so it can open the file. If it's already in memory you can try opening it as a buffer:

mime = magic.Magic(mime=True)
mime.from_buffer(f.read(2048))
  • Related