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?

2
  • Read this and this. Commented Oct 15, 2018 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 . Commented Oct 15, 2018 at 11:31

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.