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.
Advertisement
Answer
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.
JavaScript
x
4
1
for item in request.files.getlist('image'):
2
data = item.read()
3
print('len:', len(data))
4
Minimal working example:
JavaScript
1
30
30
1
from flask import Flask, request, render_template_string
2
3
app = Flask(__name__)
4
5
@app.route('/', methods=['GET', 'POST'])
6
def image():
7
if request.method == "POST":
8
#print('args :', request.args)
9
#print('form :', request.form)
10
#print('json :', request.json)
11
#print('files:', request.files)
12
print(request.files['image'])
13
print(request.files.getlist('image'))
14
15
for item in request.files.getlist('image'):
16
data = item.read()
17
print('len:', len(data))
18
19
return render_template_string('''
20
<form method="POST" enctype="multipart/form-data">
21
Single image: <input type="file" name="image"/></br>
22
Multiple images: <input type="file" name="image" multiple/></br>
23
<button type="submit" name="button" value="send">Send</button>
24
</form>
25
''')
26
27
if __name__ == '__main__':
28
#app.debug = True
29
app.run()
30