Reputation: 31
I have a Flask app in which a user uploads a file and then I make a request to google cloud vision API to classify it.
I'm doing the following:
@app.route('/cloud_vision', methods=['POST'])
def cloud_vision():
files = flask.request.files.getlist('files')
client = vision.ImageAnnotatorClient()
if len(files) > 1 or files[0].filename != '':
for file in files:
with io.open(file, 'rb') as image_file:
content = image_file.read()
image = vision.Image(content=content)
response = client.label_detection(image=image)
labels = response.label_annotations
(...)
But im getting this error TypeError: expected str, bytes or os.PathLike object, not FileStorage
when opening the file. How can I correct this?
Upvotes: 0
Views: 404
Reputation: 7287
Please note that I'm not familiar with flask but to resolve your issue you should use file.filename
in io.open()
. I used the sample code in this article to be able to use getlist()
. See code below:
app.py
from flask import Flask, render_template, request, redirect, url_for
from google.cloud import vision
import io
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/', methods=['POST'])
def upload_file():
client = vision.ImageAnnotatorClient()
files = request.files.getlist('file')
if len(files) > 1 or files[0].filename != '':
for file in files:
file.save(file.filename) # I add saving for testing
with io.open(file.filename, 'rb') as image_file: # use file.filename
content = image_file.read()
image = vision.Image(content=content)
response = client.label_detection(image=image)
labels = response.label_annotations
return str(labels)
if __name__==('__main__'):
app.run(debug=True)
index.html
<!doctype html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<h1>File Upload</h1>
<form method="POST" action="" enctype="multipart/form-data">
<p><input type="file" name="file"></p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
Testing (image used is seen here):
After submitting the image, I returned the response on the webpage.
Output after submitting the image:
Upvotes: 1