2

I have a folder containing three folders. Like this:

-folder
 -folder1
  -demo.txt
-folder2
-folder3

The Python code for uploading looks like this:

def upload():
    files = request.files.getlist('file')
    taskname = request.form.get('taskname')
    for file in files:
        file.save('/'.join(['static', taskname, file.filename]))

The HTML form contains the following components:

<input type="file" name="files" webkitdirectory>
<button id="upload-btn" type="button">upload</button>

With the above code I get the following error:

No such file or directory: 'static/task2/folder1/demo.txt'

I didn't find similar questions and solution.
Should I parse all filenames and create the folders by hand?

MrLeeh
  • 5,321
  • 6
  • 33
  • 51
yikayiyo
  • 45
  • 1
  • 4
  • Read [this](https://stackoverflow.com/questions/16351826/link-to-flask-static-files-with-url-for) and [this](https://stackoverflow.com/questions/11817182/uploading-multiple-files-with-flask). – simanacci Oct 15 '18 at 10:31
  • Thx . I first collect all folder names, add them into a set. After creating all these folders, all files are saved into the right location @roy . – yikayiyo Oct 15 '18 at 11:31

1 Answers1

2

You can also create the folders dynamically while uploading the files using pathlib. Your files will appear as shown below:

/static/files
    /task_name/ #uploaded files are here
    /task_name/ #other uploaded files  

app.py

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

app = Flask(__name__)


app.config['SECRET_KEY'] = '^%huYtFd90;90jjj'
app.config['UPLOADED_FILES'] = 'static/files'


@app.route('/upload', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST' and 'photos' in request.files:
        uploaded_files = request.files.getlist('photos')
        task_name = request.form.get('task_name')
        filename = []
        pathlib.Path(app.config['UPLOADED_FILES'], task_name).mkdir(exist_ok=True)
        for file in uploaded_files:
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOADED_FILES'], task_name, filename))
        return task_name
    return render_template('upload.html')


if __name__ == "__main__":
    app.run(debug=True)
simanacci
  • 2,197
  • 3
  • 26
  • 35