您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python – 使用Flask上传文件夹/文件

5b51 2022/1/14 8:20:21 python 字数 5174 阅读 518 来源 www.jb51.cc/python

我可以通过这个例子上传一个带烧瓶的文件: Uploading Files 但我不知道如何上传文件夹或一些文件.我搜索过,我发现了这个: Uploading multiple files with Flask.最后,我得到了如何上传多文件上传. 我会告诉你下面的代码:(这是一个好习惯吗?我不知道) @app.route('/upload/',methods = ['GET','POST']) def

概述

Uploading Files

但我不知道如何上传文件夹或一些文件.我搜索过,我发现了这个:
Uploading multiple files with Flask.最后,我得到了如何上传文件上传.
我会告诉你下面的代码:(这是一个好习惯吗?我不知道)

@app.route('/upload/',methods = ['GET','POST'])
def upload_file():
    if request.method =='POST':
        files = request.files.getlist('file[]',None)
        if files:
            for file in files:
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
            return hello()
    return render_template('file_upload.html')

但是,我仍然不知道如何上传属于该文件夹的文件夹和文件.
你能告诉我怎么样?

我正在处理的目录树:

.
├── manage.py
├── templates
│ ├── file_upload.html
│ └── hello.html
└── uploads
    ├── BX6dKK7CUAAakzh.jpg
    └── sample.txt

上传文件的源代码

from flask import Flask,abort,render_template,request,redirect,url_for
from werkzeug import secure_filename
import os
app = Flask(__name__)
UPLOAD_FOLDER = './uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER 
@app.route('/')
def index():
    return redirect(url_for('hello'))

@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name = None):
    return render_template('hello.html',name=name)

@app.route('/upload/','POST'])
def upload_file():
    if request.method =='POST':
        file = request.files['file']
        if file:
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
            return hello()
    return render_template('file_upload.html')


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

文件上传模板(manage.py):

<!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[]' multiple=''>
    <input type='submit' value='upload'>
    </p>

</form>
UPLOAD_FOLDER = './uploads'

flask找不到此目录并返回500错误.
如果你把它改为:

UPLOAD_FOLDER = '/tmp'

然后上传您的文件并导航到您将看到的/ tmp /目录.

您需要编辑正确目录的路径,以便正确上载文件.

总结

以上是编程之家为你收集整理的python – 使用Flask上传文件夹/文件全部内容,希望文章能够帮你解决python – 使用Flask上传文件夹/文件所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶