I'm supposed to get multiple image files from the requests, but I can't find a way to split a byte string request.files[key].read()
properly to make np.ndarrays
out of them.
CodePudding user response:
files[key]
gives only one object which has name=key
in HTML
, and .read()
gives data only for this single file. So there is no need to split it.
If you have many files with name=key
then you need files.getlist(key)
to get list with all files and next use for
-loop to read every file separatelly.
for item in request.files.getlist('image'):
data = item.read()
print('len:', len(data))
Minimal working example:
from flask import Flask, request, render_template_string
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def image():
if request.method == "POST":
#print('args :', request.args)
#print('form :', request.form)
#print('json :', request.json)
#print('files:', request.files)
print(request.files['image'])
print(request.files.getlist('image'))
for item in request.files.getlist('image'):
data = item.read()
print('len:', len(data))
return render_template_string('''
<form method="POST" enctype="multipart/form-data">
Single image: <input type="file" name="image"/></br>
Multiple images: <input type="file" name="image" multiple/></br>
<button type="submit" name="button" value="send">Send</button>
</form>
''')
if __name__ == '__main__':
#app.debug = True
app.run()