加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 21:32:39 所属栏目:Python 来源:网络整理
导读:我可以通过这个例子上传一个带烧瓶的文件: Uploading Files 但我不知道如何上传文件夹或一些文件.我搜索过,我发现了这个: Uploading multiple files with Flask.最后,我得到了如何上传多文件上传. 我会告诉你下面的代码:(这是一个好习惯吗?我不知道) @app
我可以通过这个例子上传一个带烧瓶的文件:

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>

解决方法

这里的问题是,烧瓶的app.config与自身无关,这是绝对的.所以当你把:
UPLOAD_FOLDER = './uploads'

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

UPLOAD_FOLDER = '/tmp'

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读