'python - cannot detect if file uploaded in request.files
Im using python3 and i want to detect if a file has uploaded , for some reason i get the same result if i upload a file and if i dont upload.
HTML code:
<h3>Add new customer:</h3>
<form method="post" action="customerAdd" style="display: inline;" enctype="multipart/form-data">
<label for="customer">Customer name:</label>
<input type="text" id="customer" name="customer" required>
<input type="file" name="file" accept="text" multiple/>
<input value="Submit" type="submit" onclick="clicked(event)"/>
</form>
python code:
@app.route("/customerAdd", methods=["GET","POST"])
def customer_add():
data = dict(request.form)
files = request.files
c.print_info("FILE", files)
c.print_info("info", request.files.get('filepath'))
c.print_info("Len", len(request.files))
If i upload a file this what i see in the logs:
'FILE', ImmutableMultiDict([('file', <FileStorage: 'abc.txt' ('text/plain')>), ('file', <FileStorage: 'abc2.txt' ('text/plain')>)]
api_1 | 1647179071 [61], INF, info (None,)
api_1 | 1647179071 [61], INF, Len (1,)
And if empty:
'FILE', ImmutableMultiDict([('file', <FileStorage: '' ('application/octet-stream')>)])
api_1 | 1647179071 [61], INF, info (None,)
api_1 | 1647179071 [61], INF, Len (1,)
I have tried to use like all suggest with:
len(request.files) != 0:
But i get the same reasult, the only difference is the "FILE" log that prints request.files output is without any filename inside. What am i doing wrong ? Thanks!
Solution 1:[1]
Assuming you are using Flask (if not specify your question!) you should be able to use:
# "file" is comes from the name: of your input tag
files = flask.request.files.getlist("file")
for file in files:
if file.filename !='':
# Do something with file, file.save() etc.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | stuckonhere |
