使用Flask上传文件夹/文件

时间:2013-11-11 03:17:15

标签: python file-upload flask

我可以通过这个例子上传一个带烧瓶的文件:

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/',methods = ['GET','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>

2 个答案:

答案 0 :(得分:3)

file = request.files['file']

将其更改为

file = request.files['file[]']

答案 1 :(得分:2)

这里的问题是,烧瓶的app.config与自身并不相关,它是绝对的。所以当你把:

UPLOAD_FOLDER = './uploads' 

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

UPLOAD_FOLDER = '/tmp'  

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

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

相关问题