【发布时间】:2015-12-16 04:15:05
【问题描述】:
我正在尝试创建一个 Flask 应用程序,其中的一些功能包括用户能够将图像上传到他们自己的静态文件夹目录中。
我的代码基于https://github.com/kirsle/flask-multi-upload,实际上它基本相同(除了 AJAX 功能)所以我真的看不出哪里出错了(我自己运行了 kirsle 的应用程序环境 - 它工作正常)。
当我访问/static/uploads/{uuid_goes_here}/img.jpg 时,我可以看到图片 - 很明显它正在上传。然而访问/files/{uuid_goes_here} 会导致if not os.path.isdir(location) 被执行。
当我注释掉这段代码并尝试直接进入 complete.html 时,{% for file in files %} 似乎没有运行,因为没有图像出现。
我的代码是:
app.py
# Route that will process the file upload
@app.route('/upload', methods=['POST'])
def upload():
form = request.form
username = current_user.username #for later when I replace uuid's with usernames
uuid_key = str(uuid4())
print("Session Key: {}".format(uuid_key))
target = "static/uploads/{}".format(uuid_key)
try:
os.mkdir(target)
except FileExistsError:
return "Couldn't create directory {}".format(target)
for upload in request.files.getlist("file"):
filename = upload.filename.rsplit("/")[0]
destination = '/'.join([target, filename])
print( "Accepting: {}\n and saving to: {}".format(filename, destination))
upload.save(destination)
return redirect(url_for('complete', uuid_key=uuid_key))
@app.route("/files/<uuid_key>")
def complete(uuid_key):
location = "/static/uploads/{}".format(uuid_key)
if not os.path.isdir(location):
return "Error! {} not found!".format(location)
files = []
for file in glob.glob("{}/*.*".format(location)):
fname = file.split(os.sep)[-1]
files.append(fname)
return render_template('complete.html', uuid=uuid_key, files=files)
complete.html
{% extends 'layout.html' %}
{% block content %}
{% for file in files %}
<h2>{{ file }}</h2>
<img src="{{ url_for('static', filename='/uploads/{}/{}'.format(uuid, file)) }}">
{% endfor %}
{% endblock %}
post.html
{% extends 'layout.html' %}
{% block content %}
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" accept="image/*"><br /><br />
<input type="submit" value="Upload">
</form>
{% endblock %}
我已将我的代码与 kirsle 的代码进行了比较,但我看不出哪里出错了。
【问题讨论】:
-
奇怪的是你的根路径上有你的静态目录? “/static”是完整路径,与当前文件无关。
-
尝试 location = "static/uploads/{}".format(uuid_key) 只要这是在一个简单的 app.py 文件中运行,其中静态相对于 app.py 文件
标签: python python-3.x flask uuid glob