1

I need to have a feature on my Flask app to let users upload whole folders, not the files within them but to also keep the whole tree of folders. Is there a special feature within Flask or do I need to create a code with loops using the single file uploading methods?

Thanks in advance

Myssalyne
  • 11
  • 2
  • Welcome to Stack Overflow! Could you edit your question to include some code from your current app? If you already have an upload form and some code that processes the upload, including them would help others to give you a tailored solution. Have you looked into answers to similar questions? This one might be helpful https://stackoverflow.com/questions/22041207/is-it-possible-to-upload-a-folder-using-html-form-php-script – Nikolay Shebanov Mar 12 '21 at 10:11

1 Answers1

1

Chrome supports uploading folders and with Flask we can get a list of files to save.

upload.html

<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form action='' method="POST" enctype="multipart/form-data">
    <p><input type="file" name="file[]" webkitdirectory="" directory="">
    <input type='submit' value='upload'>
    </p>

</form>

main.py

from flask import Flask, render_template, request, redirect, url_for
from werkzeug.utils import secure_filename
import os

app = Flask(__name__)
UPLOAD_FOLDER = '/path/to/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER 

@app.route('/upload/',methods = ['GET','POST'])
def upload_file():
    if request.method =='POST':
        files = request.files.getlist("file[]")
        print(request.files)
        for file in files:
            path = os.path.dirname(file.filename)
            path2 = os.path.join(app.config['UPLOAD_FOLDER'], path)
            if not os.path.exists(path2):
                os.mkdir(path2)
            filename = os.path.join(path, secure_filename(os.path.basename(file.filename)))
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return 'Files uploaded.'
    return render_template('upload.html')


if __name__ == '__main__':
    app.run(debug = True)
tomasantunes
  • 814
  • 2
  • 11
  • 23
  • 1
    Thank you a lot! I tried this but I still can't select several files nor a folder when browsing for the upload. Do you know why? – Myssalyne Mar 14 '21 at 13:57