【问题标题】:Wrong size in bytes being displayed using BytesIO in Django在 Django 中使用 BytesIO 显示的字节大小错误
【发布时间】:2021-07-05 15:31:40
【问题描述】:

我正在尝试在使用 django 将图像上传到数据库之前对其进行验证,但无论我做什么似乎都无法获得准确的图像大小

view.py:

def upload_image(request):                       #used to upload images in document_upload
    c = main.objects.get(username = request.session['username'])
    unq_id = c.unq_id
    if request.method == 'POST':
        images = request.FILES.getlist('image')
        name = request.POST['name']
        for x in images:
            img = Image.open(x)
            img_file = BytesIO()
            img.save(img_file, 'jpeg')
            image_file_size = img.tell()

            if image_file_size > 150 * 1024:
                print(image_file_size)
                failure = "image needs to be lesser dimenstion than 150kb"
                return render(request, 'Main/document_upload.html', {'failure':failure})
            else:
                print(image_file_size)
                fs = FileSystemStorage()
                filename = fs.save(x.name, x)
                Doc1 = Doc(user_id = unq_id, upload = x, name = name)
                Doc1.save()
                success = "You have successfully added documents, proceed to 'My documents' to see your documents"
    return render(request, 'Main/document_upload.html', {'success':success})

在打印 print(image_file_size) 时,我的值似乎比其属性中显示的大小要小得多

示例print(image_file_size) 显示1295,而实际上大小为8537

我该如何解决这个问题?谢谢

【问题讨论】:

  • 在调用.tell()之前尝试使用.seek(0, 2)

标签: python django byte


【解决方案1】:

好的,所以答案很简单,事实证明阅读文档可以解决所有问题,而且不和谐社区也非常有帮助,尤其是一个名叫 @zylon 的人

原来文件对象有一个叫做 size 的方法,它给出了准确的值:

ie x.size 会为您提供准确的文件大小(与属性中显示的相同)

PS:https://docs.djangoproject.com/en/3.2/ref/files/file/ 这会有所帮助

【讨论】:

    猜你喜欢
    • 2023-03-14
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多