Why does request.FILES[“file”].open() is None, tho

2019-08-28 02:22发布

I'm trying to get image file using ajax into Django views.py. I can print the file name and size of it. But when I open the file, it become None..!

The reason I'm trying to open image is to use it for vision analysis. Currently I'm working on Django 1.11, python 3.6.7.

Here are some codes.

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

ajax part in html

                $.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);
                    }
                });

I expected the receipt_image in views.py is binary of the image file. But It's empty. Because request.FILES["file"] is None. I don't know why it's None.

Thanks your for reading my question. Hope you have a good day

1条回答
我想做一个坏孩纸
2楼-- · 2019-08-28 02:54

Once you have called read() on a file subsequent calls will not yield any data. The first call to read() reads the entire buffer and there will not be anything left when you call it again

    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''
查看更多
登录 后发表回答