python - 通过 Flask 上传多个文件或整个文件夹

标签 python file flask file-upload web-applications

我需要创建一个实用程序,可以通过 Flask 存储整个文件夹、文件夹或文件,目前我正在使用以下代码一次上传 1 个文件

flask 代码:

from flask import Flask, render_template, request

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':
      f = request.files['file']
      f.save(secure_filename(f.filename))
      return 'file uploaded successfully'

if __name__ == '__main__':
   app.run(debug = True)

html代码:

<html>
   <body>
      <form action = "http://localhost:5000/uploader" method = "POST" 
         enctype = "multipart/form-data">
         <input type = "file" name = "file" />
         <input type = "submit"/>
      </form>
   </body>
</html>

我收到以下对话框:

dialog box

但这只允许我一次插入一个文件。

我需要一些可以让我上传整个目录或多个文件的东西。可以使用 Flask 来完成吗?如果没有,Python 有没有其他可用的替代方案?任何有关此事的帮助将不胜感激!

最佳答案

答案:

html 文件

<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>

在输入标记中,multiple 是允许访问多个文件的强制参数!

flask 代码:

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)

使用flask.request.getlist获取目录中的文件列表。 要处理多个文件,只需使用循环来管理它们,如上所示。

关于python - 通过 Flask 上传多个文件或整个文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60167773/

相关文章:

python - 通过 pandas to_sql 命令检查数据库插入结果 - Flask

file - 执行上传时未定义的文件属性

java - 如何在Java中将静态类保存到文件中?

python - Flask View 的类型注释是什么?

docker - 带 docker 的 Flask 调试控制台不起作用

python - 根据第一个子模型的属性对查询集进行排序,会返回重复的对象。 Django ,DRF

python - 跳过从正则表达式中的字符开始

python - 使用多个数据框创建 pandas 数据框

c++ - 列出文件夹中的所有文件返回空列表

python - 为什么我刷新页面WTForms会重新提交?