1

我需要在我的 Flask 应用程序上提供一个功能,让用户上传整个文件夹,而不是其中的文件,但还要保留整个文件夹树。Flask 中是否有特殊功能,或者我是否需要使用单个文件上传方法创建带有循环的代码?

提前致谢

4

1 回答 1

0

Chrome 支持上传文件夹,使用 Flask 我们可以获得要保存的文件列表。

上传.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>

主文件

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)
于 2021-03-12T10:53:29.320 回答