I'm having a similar issue. I've seen it recommended to use request.files.getlist("file[]") or request.files.getlist("file") << this worked for me for 2 files but when I started upload 3 separate files via 3 form elements I would only get 2. So here's the code I'm using right now.
for file in request.files:
files[file].save(out_filename)
Answer from kkron on Stack OverflowI'm having a similar issue. I've seen it recommended to use request.files.getlist("file[]") or request.files.getlist("file") << this worked for me for 2 files but when I started upload 3 separate files via 3 form elements I would only get 2. So here's the code I'm using right now.
for file in request.files:
files[file].save(out_filename)
I don't know if you still need help with this. But I had the same problem and I think I found a solution. Well, in my case, I am using an ajax request to send the files.
I realized that when I indexed in the var used to send the files, in python I got just one file and after I found this example.
So using this example as reference.
JavaScript Code:
var form_data = new FormData();
var auxnames = "";
var wordsF = $("#word").prop("files");
$.each(wordsF, function(i, file){
form_data.append(file.name, file);
auxnames += file.name+',';
});
form_data.append('auxindex', auxnames);
$.ajax({
url: $SCRIPT_ROOT + "/upload_files",
type:"post",
data:form_data,
contentType: false,
cache: false,
processData: false,
}).done(function(response){ ...
Python code:
if request.method == 'POST':
auxindex = request.form['auxindex']
auxindex = auxindex.split(",")
auxindex = list(filter(None, auxindex))
for file in auxindex:
auxfile = request.files[file]
namefile = secure_filename(file)
auxfile.save(os.path.join(path, namefile))
maybe isn't the best way but it works for me, I hope this would be useful for you.
Request multiple files - New update old syntax does not work
Flask request.files.getlist unable to loop through multiple files
python - Get the data received in a Flask request - Stack Overflow
python - Flask - request.files.getlist() - do not skip empty - Stack Overflow
Videos
You can use method getlist of flask.request.files, for example:
@app.route("/upload", methods=["POST"])
def upload():
uploaded_files = flask.request.files.getlist("file[]")
print uploaded_files
return ""
@app.route('/upload', methods=['GET','POST'])
def upload():
if flask.request.method == "POST":
files = flask.request.files.getlist("file")
for file in files:
file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
It works for me.
for UPLOAD_FOLDER if you need add this just after app = flask.Flask(name)
UPLOAD_FOLDER = 'static/upload'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
The docs describe the attributes available on the request object (from flask import request) during a request. In most common cases request.data will be empty because it's used as a fallback:
request.dataContains the incoming request data as string in case it came with a mimetype Flask does not handle.
request.args: the key/value pairs in the URL query stringrequest.form: the key/value pairs in the body, from a HTML post form, or JavaScript request that isn't JSON encodedrequest.files: the files in the body, which Flask keeps separate fromform. HTML forms must useenctype=multipart/form-dataor files will not be uploaded.request.values: combinedargsandform, preferringargsif keys overlaprequest.json: parsed JSON data. The request must have theapplication/jsoncontent type, or userequest.get_json(force=True)to ignore the content type.
All of these are MultiDict instances (except for json). You can access values using:
request.form['name']: use indexing if you know the key existsrequest.form.get('name'): usegetif the key might not existrequest.form.getlist('name'): usegetlistif the key is sent multiple times and you want a list of values.getonly returns the first value.
For URL query parameters, use request.args.
search = request.args.get("search")
page = request.args.get("page")
For posted form input, use request.form.
email = request.form.get('email')
password = request.form.get('password')
For JSON posted with content type application/json, use request.get_json().
data = request.get_json()
request.files is populated with whatever the client submitted. Unfortunately, browsers submit file inputs even when no file is selected, which looks like a file with no name and no data. Neither a name or data is required to have a valid empty file, so it's left up to the app to decide what to do.
FileStorage will be considered False if it has no name. Flask-WTF considers a FileStorage with no name to be empty for validation.
photo = request.files["photo"]
if not photo:
# no photo
photos = request.files["photo"].getlist()
if not photos or not any(f for f in photos):
# no photos
Regarding Empty File Storage Object, means if File field is left empty while submitting form and you are getting a empty file storage object ,and want to filter it.you can apply the below mentioned check.
if not (all(isinstance(item, FileStorage) for item in field.data) and
field.data and all((item.filename != '') for item in field.data)):
return
for no files uploaded, FileStorage objects filename attribute is like field.data.file.filename = '', so that we can filter it based on this condition.