【问题标题】:Get MIME type of file that is in memory - Python Django获取内存中文件的 MIME 类型 - Python Django
【发布时间】:2022-01-18 06:36:41
【问题描述】:

我有一个用户可以上传文件的表单。我只希望他们能够上传图片。我已在 HTML 表单中添加了该内容,但需要进行服务器端检查。我想在将文件保存到 AWS S3 之前进行此检查。

目前我有这个:

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')

但是,我收到此错误: TypeError:预期的 str、bytes 或 os.PathLike 对象,而不是 BytesIO

如何正确地将图像传递给魔法?

谢谢

【问题讨论】:

    标签: python django mime-types


    【解决方案1】:

    Magic 期望 from_file 的参数是一个路径,因此它可以打开文件。如果它已经在内存中,您可以尝试将其作为缓冲区打开:

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

    【讨论】:

      猜你喜欢
      • 2020-07-21
      • 2018-12-01
      • 2011-05-27
      • 2014-05-19
      • 1970-01-01
      • 2012-05-08
      • 1970-01-01
      • 2010-09-30
      • 2014-08-06
      相关资源
      最近更新 更多