【问题标题】:Why does request.FILES["file"].open() is None, though request.FILES.["file"].name works well?为什么 request.FILES["file"].open() 是 None,尽管 request.FILES.["file"].name 效果很好?
【发布时间】:2019-12-24 05:40:57
【问题描述】:

我正在尝试使用 ajax 将图像文件放入 Django views.py。 我可以打印它的文件名和大小。但是当我打开文件时,它变成了 None..!

我尝试打开图像的原因是为了将其用于视觉分析。 目前我正在开发 Django 1.11、python 3.6.7。

这里有一些代码。

views.py

def receipt_ocr(request):
    if request.method == 'POST':
        print(type(request.FILES["file"]))              #<class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
        print(request.FILES["file"])                    #bank.png
        print(request.FILES["file"].size)               #119227
        print(request.FILES["file"].name)               #bank.png
        print(request.FILES["file"].content_type)       #image/png
        print(type(request.FILES["file"].open()))       #<class 'NoneType'>
        print(request.FILES["file"].open())             #None
        print(type(request.FILES["file"].read()))       #<class 'bytes'>
        imageFile = request.FILES["file"]
        receipt_image = imageFile.read()
        print(type(receipt_image))                      #<class 'bytes'>
        print(receipt_image)                            #b''

html中的ajax部分

                $.ajax({
                    url: "{% url 'ocr:receipt_ocr' %}",
                    enctype: 'multipart/form-data',
                    type: 'POST',
                    cache: false,
                    processData: false,
                    contentType: false,
                    data: postData,
                    complete: function(req){
                        alert('good');
                    },
                    error: function(req, err){
                        alert('message:' + err);
                    }
                });

我预计views.py 中的receipt_image 是图像文件的二进制文件。但它是空的。因为 request.FILES["file"] 是无。我不知道为什么它是无。

感谢您阅读我的问题。 希望你有美好的一天????

【问题讨论】:

    标签: python django ajax forms python-requests


    【解决方案1】:

    一旦您对文件调用了read(),后续调用将不会产生任何数据。第一次调用read() 会读取整个缓冲区,再次调用时不会有任何剩余

        print(type(request.FILES["file"].read())) # This line has read the entire buffer
        imageFile = request.FILES["file"]
        receipt_image = imageFile.read() # There is nothing left to read so this returns b''
    

    【讨论】:

    • 这正是我错过的。它真的很好用。谢谢你,谢尔文顿!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-20
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多