【问题标题】:Upload multiple files or a whole folder through Flask通过 Flask 上传多个文件或整个文件夹
【发布时间】:2020-05-26 19:07:30
【问题描述】:

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

烧瓶代码:

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>

我收到以下对话框:

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

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

【问题讨论】:

标签: python file flask file-upload web-applications


【解决方案1】:

答案:

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是允许访问多个文件的强制参数!

烧瓶代码:

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 获取目录中的文件列表。 要处理多个文件,只需使用循环来管理它们,如上所示。

【讨论】:

  • 在客户端,我将 webkitdirectory mozdirectory 添加到表单输入中,如下所示,并且能够上传包括嵌套文件在内的整个文件夹。服务器代码或多或少是一样的(区别只是我自己的逻辑。)我在Firefox中测试过:
猜你喜欢
  • 1970-01-01
  • 2017-01-16
  • 2019-12-23
  • 1970-01-01
  • 2012-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多