Uploading multiple files with Flask
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 ""
Upload multiple files or a whole folder through Flask
answer:
html file
<html>
<body>
<form action = "http://localhost:5000/uploader" method = "POST"
enctype = "multipart/form-data">
<input type = "file" name = "file" multiple/>
<input type = "submit"/>
</form>
</body>
</html>
in the input tag, multiple is a mandatory argument to allow access of multiple files!
flask code:
from flask import Flask, render_template, request
#from werkzeug import secure_filename
from werkzeug.utils import secure_filename
app = Flask(__name__)
@app.route('/')
def upload_file():
return render_template('upload.html')
@app.route('/uploader', methods = ['GET', 'POST'])
def upload_file1():
if request.method == 'POST':
files = request.files.getlist("file")
for file in files:
file.save(secure_filename(file.filename))
return 'file uploaded successfully'
if __name__ == '__main__':
app.run(debug = True)
Use flask.request.getlist to get the list of files in the directory.
To process multiple files just use a loop to manage them as shown above.
How to upload multiple files in flask?
You are not getting the list of files that is why you do not get multiple files. You need to access the list of files from the form which comes from the username input.
from flask import Flask, render_template, url_for, session, redirect, request
from image_initial import Image_tensorflow
app = Flask(__name__, template_folder='templates')
app.config['SECRET_KEY'] = 'mykeyhere'
@app.route('/', methods=['GET', 'POST'])
def test():
if "file_urls" not in session:
session['file_urls'] = []
file_urls = session['file_urls']
if request.method == 'POST':
file_obj = request.form.getlist("username")
session['file_urls'] = file_obj
return redirect(url_for('results'))
return render_template("test.html")
@app.route('/results')
def results():
if "file_urls" not in session or session['file_urls'] == []:
print('session is not created')
return redirect(url_for('test'))
file_urls = session['file_urls']
Image_tensorflow(file_urls, file_urls)
session.pop('file_urls', None)
return render_template('results.html', file_urls=file_urls)
if __name__ == "__main__":
app.run(host='0.0.0.0')
Above code will give you the list of files. However, I have not tested it whole so you might need to make little modifications if some other things do not work
EDIT:
in the stack trace it seems that the problem is with lineImage.open(xa)
Here xa is a list of images and Image.open()
does not expect a list what you can do is iterate through each image and the open it.
for img in xa:
Image.open(img)
Flask - Upload Multiple Files
The problem with your attempt has nothing to do with Flask - it is a "Python" problem.
You iterate over all uploaded files, but you break the for-loop with the return
statement (return render_template(...)
.
So, you have to iterate over all files, and then, only outside the for-loop return.
Simple example
for fruit in ['apple', 'bananas']:
print(fruit)
return # too early!!
for fruit in ['apple', 'bananas']:
print(fruit)
return # <- right time to return
upload multiple files with fetch
I don't use React
but for me problem makes
formData.append("file", this.state.file);
because this.state.file
is list with one or many files and it needs for
-loop to add every file as separated object in Form
const formData = new FormData();
var totalfiles = this.state.file.length;
for (var index=0; index < totalfiles; index++){
formData.append("file", this.state.file[index]);
}
And now it sends all files in request.files
instead of one (useless) string '[object File],[object File]'
in request.form
Minimal working code
from flask import Flask, request, render_template_string
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
return render_template_string('''
<!DOCTYPE html>
<script>
this.state = {
file: []
}
fileSelectHandler = (event) => {
console.log("fileSelectHandler");
var totalfiles = event.target.files.length;
for (var index=0; index < totalfiles; index++){
this.state.file.push(event.target.files[index]);
}
}
async function onFormSubmit(event) {
console.log("onFormSubmit");
event.preventDefault();
const formData = new FormData();
var totalfiles = this.state.file.length;
for (var index=0; index < totalfiles; index++){
formData.append("file", this.state.file[index]);
}
// doesn't need `http://.../` if sends to the same server
await fetch('/photo/create',
{
method: 'POST',
body: formData,
});
}
</script>
<input type="file" multiple onChange="fileSelectHandler(event);">
<button type="submit" onClick="onFormSubmit(event);">Submit</button>
''')
@app.route('/photo/create', methods=['GET', 'POST'])
def photo():
print('args :', request.args)
print('form :', request.form)
print('json :', request.json)
print('files:', request.files)
for file in request.files.getlist('file'):
print(file.filename)
#print(file.read())
return render_template_string(''' ''')
if __name__ == '__main__':
#app.debug = True
app.run()
How to upload multiple files separately in Flask?
please make sure that use same input field names(mentioned in upload.html) in main.py
Here is the working solution , which will takes only 'xml', 'mxl','mid','wav' extensions,
we can remove multiple upload field if we want, but as per your requirement I modified.
Thanks
app.py
from flask import Flask
UPLOAD_FOLDER = '/root/Flask'
app = Flask(__name__)
app.secret_key = "secret key"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
main.py
import os
import magic
from app import app
from flask import Flask, flash, request, redirect, render_template
from werkzeug.utils import secure_filename
ALLOWED_EXTENSIONS = set(['xml', 'mxl','mid','wav'])
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/')
def upload_form():
return render_template('upload.html')
@app.route('/', methods=['POST'])
def upload_file():
if request.method == 'POST':
print(request.__dict__)
# check if the post request has the file part
if 'sfile' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['sfile']
if file.filename == '':
flash('No file selected for uploading')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
flash('File successfully uploaded')
return redirect('/')
else:
flash('Allowed file types are xml,mxl,mid,wav')
return redirect(request.url)
if __name__ == "__main__":
app.run(host="0.0.0.0",port=int("5003"),debug=True)
templates/upload.html
<!doctype html>
<title>Python Flask File Upload Example</title>
<h2>Step 1: Select a sheet music file (.xml, .mxl or .mid) to upload</h2>
<p>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
</p>
<form method="post" name="sform" action="/" enctype="multipart/form-data">
<dl>
<p>
<input type="file" name="sfile" autocomplete="off" required>
</p>
</dl>
<p>
<input type="submit" name="ssubmit" value="Submit">
</p>
</form>
<h2>Step 2: Select a wav file to upload</h2>
<form method="post" name="wform" action="/" enctype="multipart/form-data">
<dl>
<p>
<input type="file" name="sfile" autocomplete="off" required>
</p>
</dl>
<p>
<input type="submit" name="wsubmit" value="Submit">
</p>
</form>
Related Topics
Builtin Function Not Working with Spyder
Compare Two CSV Files and Search for Similar Items
Convert Words Between Verb/Noun/Adjective Forms
Pandas - Convert Strings to Time Without Date
Writing Utf-8 String to MySQL with Python
Operationalerror: Database Is Locked
Matplotlib Bar Chart with Dates
Python Requests.Exceptions.Sslerror: Eof Occurred in Violation of Protocol
Why Do Attribute References Act Like This with Python Inheritance
Is There Any Built-In Way to Get the Length of an Iterable in Python
Access Memory Address in Python
How to Redirect Print Statements to Tkinter Text Widget
File Read Using "Open()" VS "With Open()"
Pandas Filling Missing Dates and Values Within Group
How to Timeout Function in Python, Timeout Less Than a Second