如何阅读 Django 请求.文件(这是一个图像)作为二进制



我想从请求中获取一个二进制图像,其中包含来自 ajax 的图像文件。

Senario - 当用户上传图像文件时,我想使用谷歌视觉API对图像文件进行OCR(光学字符识别(。为此,我需要将文件读取为二进制文件。

背景 - 目前,在我的程序中,当用户上传图像时,文件由 ajax 传递给 Django 视图。我试图在 views.py 中获取一个二进制文件。当我使用request.FILES.get('file').read()时,没有数据。 但print(request.FILES.get('file').name)是"银行.png"...我觉得这很奇怪。

这是一些代码

views.py

def receipt_ocr(request):
if request.method == 'POST':
print(type(request.FILES["file"]))              #<class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
print(type(request.FILES.get('file')))          #<class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
print(request.FILES.get('file'))                #bank.png
imageFile = request.FILES.get('file')
print(imageFile.size)                           #119227
print(request.FILES.get('file').name)           #bank.png
print(request.FILES.get('file').content_type)   #image/png
print(type(request.FILES.get('file').open()))   #<class 'NoneType'>
print(request.FILES.get('file').open())         #None
print(type(request.FILES["file"].read()))       #<class 'bytes'>
for chunk in imageFile.chunks():
print(chunk)                               #this generates lot of binary and some rdf:Description rdf:about= ... things
receipt_image = imageFile.read()
print(type(receipt_image))
print(receipt_image)

阿贾克斯部分


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

我真正想做的是使用这种代码(谷歌视觉API示例代码,OCR(

def detect_text(path):
"""Detects text in the file."""
client = vision.ImageAnnotatorClient()
with io.open(path, 'rb') as image_file:
content = image_file.read() #read binary, save to content
image = vision.types.Image(content=content)
response = client.text_detection(image=image)
texts = response.text_annotations
print('Texts:')
print(type(texts))
for text in texts:
print('n"{}"'.format(text.description))
vertices = (['({},{})'.format(vertex.x, vertex.y)
for vertex in text.bounding_poly.vertices])
print('bounds: {}'.format(','.join(vertices)))

所以我想从请求中获取我 views.py 中上述代码的"内容"。 (我不需要使用这个函数本身。我将使用函数的某些部分(

如何在 views.py 中获取二进制映像? 我以为下面的代码会起作用,但它不起作用。 我不知道为什么。

f = request.FILES.get('file')
receipt_image = f.read()
image = vision.types.Image(content=receipt_image)

感谢您的任何帮助和意见。

===ADD===

"它不起作用"意味着我从日志中得到了这个回溯。

Internal Server Error: /mdd_event/receipt_ocr/ Traceback (most recent call last): File "C:Usersuserliamdevgitmdd_bean_envlibsite-packagesgoogleapi_coregrpc_helpers.py", line 57, in error_remapped_callable return callable_(*args, **kwargs) 
File "C:Usersuserliamdevgitmdd_bean_envlibsite-packagesgrpc_channel.py", line 565, in __call__ return _end_unary_response_blocking(state, call, False, None) 
File "C:Usersuserliamdevgitmdd_bean_envlibsite-packagesgrpc_channel.py", line 467, in _end_unary_response_blocking raise _Rendezvous(state, None, None, deadline) grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with: status = StatusCode.INVALID_ARGUMENT details = "Request must specify image and features." debug_error_string = "{"created":"@1566165461.211000000","description":"Error received from peer ipv4:216.58.197.234:443","file":"src/core/lib/surface/call.cc","file_line":1052,"grpc_message":"Request must specify image and features.","grpc_status":3}" > 
The above exception was the direct cause of the following exception: Traceback (most recent call last): 
File "C:Usersuserliamdevgitmdd_bean_envlibsite-packagesdjangocorehandlersexception.py", line 41, in inner response = get_response(request) 
File "C:Usersuserliamdevgitmdd_bean_envlibsite-packagesdjangocorehandlersbase.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) 
File "C:Usersuserliamdevgitmdd_bean_envlibsite-packagesdjangocorehandlersbase.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) 
File "C:Usersuserliamdevgitmdd_bean_envlibsite-packagesdjangocontribauthdecorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) 
File "C:Usersuserliamdevgitmdd_bean_envlibsite-packagesdjangocontribauthdecorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) 
File "C:Usersuserliamdevgitmdd_beanmdd_eventviews.py", line 530, in receipt_ocr response = client.text_detection(image=image) 
File "C:Usersuserliamdevgitmdd_bean_envlibsite-packagesgooglecloudvision_helpersdecorators.py", line 101, in inner response = self.annotate_image(request, retry=retry, timeout=timeout) 
File "C:Usersuserliamdevgitmdd_bean_envlibsite-packagesgooglecloudvision_helpers__init__.py", line 72, in annotate_image r = self.batch_annotate_images([request], retry=retry, timeout=timeout) 
File "C:Usersuserliamdevgitmdd_bean_envlibsite-packagesgooglecloudvision_v1gapicimage_annotator_client.py", line 274, in batch_annotate_images request, retry=retry, timeout=timeout, metadata=metadata File "C:Usersuserliamdevgitmdd_bean_envlibsite-packagesgoogleapi_coregapic_v1method.py", line 143, in __call__ return wrapped_func(*args, **kwargs) 
File "C:Usersuserliamdevgitmdd_bean_envlibsite-packagesgoogleapi_coregrpc_helpers.py", line 59, in error_remapped_callable six.raise_from(exceptions.from_grpc_error(exc), exc) 
File "<string>", line 3, in raise_from google.api_core.exceptions.InvalidArgument: 400 Request must specify image and features.

我发布了另一个问题。因为这个问题包括的不是一个问题,而是一些问题,例如"没有实际数据,但名称和大小","获取二进制图像","谷歌视觉api使用",... 所以我决定再发布一个"无数据"问题。有答案

总结:我已经阅读了request.FILES["file"].read()中的数据。因此,后续调用的缓冲区中没有数据。

最新更新