17

我可以按照上传文件上传带有烧瓶的文件

  1. 一个<form>标签被标记,enctype=multipart/form-data一个<input type=file>被放置在那个表格中。
  2. 应用程序从请求对象的文件字典中访问文件。
  3. 使用文件的save()方法将文件永久保存在文件系统的某个位置。

但我不知道如何上传文件夹或一些文件。我搜索了,我发现Uploading multiple files with Flask

但是,我仍然不知道如何上传文件夹和属于该文件夹的文件。

你能告诉我怎么做吗?


我正在处理的目录树:

.
├── 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>
4

2 回答 2

8
file = request.files['file']

将其更改为

file = request.files['file[]']
于 2017-01-16T05:45:37.703 回答
6

the issue here is that flask's app.config isn't relative to itself, it's absolute. so when you put:

UPLOAD_FOLDER = './uploads' 

flask doesn't find this directory and returns a 500 error. if you changed it to:

UPLOAD_FOLDER = '/tmp'  

and then uploaded your file and navigated to the /tmp/ directory you would see it.

you will need to edit your path to the proper directory for the file to be uploaded properly.

于 2015-01-23T00:36:36.607 回答