我目前正在尝试建立一个flask应用程序,它将接受一个上传的图像,允许用户应用过滤器到该图像,然后让用户查看他们的上传和过滤的图像库。 我有一个名为upload()
的方法和一个模板upload.html
,它们打印在下面的代码片段中--我根据用于在flask中上传图像的教程尝试了三个不同版本的upload()
,每一个都有相同的结果。 带有表单的上传模板正常加载,我上传了一个图像,然后我得到一个内部服务器错误。 我返回到我的IDE中的终端(我使用的是CS50 IDE)检查错误来自哪里,并且没有任何回溯。
奇怪的是,我的第二次和第三次尝试是基于我所看到的教程来实现的,在这些教程中,完全相同的实现工作得很好。
以下是HTML模板:
{% extends "layout.html" %}
{% block title %}
Upload
{% endblock %}
{% block main %}
<form action="/upload" method="post" enctype=multipart/form-data>
<input type="file" name="image">
<input type="submit" value="Upload">
</form>
{% endblock %}
upload()
的第一个版本:
@app.route("/upload", methods=['GET', 'POST'])
def upload():
if request.method == 'GET':
return render_template("upload.html")
if request.files:
#The POST request came through with an image file.
image = request.files['image']
if image.filename == "":
print("No filename")
return redirect("/upload")
if image and allowed_image(image.filename):
filename = secure_filename(image.filename)
image.save(os.path.join(app.config['IMAGE_UPLOADS'], filename))
print("Image saved.")
return redirect("/")
else:
print("That file extension is not allowed")
return redirect("/upload")
else:
print("Not request.files")
return render_template("upload.html")
第二个,photos=UploadSet('photos',IMAGES)
,使用flask_uploads
扩展名:
@app.route("/upload", methods=['GET', 'POST'])
def upload():
if request.method == 'POST' and 'photo' in request.files:
filename = photos.save(request.files['photo'])
print(filename)
return redirect("/")
return render_template('upload.html')
第三个:
def upload():
if request.method == 'POST':
target = os.path.join(APP_ROOT, "images/")
print(target)
if not os.path.isdir(target):
os.mkdir(target)
for file in request.files.getlist("image"):
print(file)
filename = file.filename
destination = "/".join([target, filename])
print(destination)
file.save(destination)
return render_template("index.html")
else:
return render_template("upload.html")
使用flask_uploads
[pip install flask_uploads
]上传文件非常容易。 这样,您就不必为上传文件编写样板代码了。 注意-如果遇到“无法从”werkzeug“导入名称'secure_filename'”的问题,您可能必须以pip install werkzeug==0.16.0
的形式安装特定版本的werkzeug
下面是我在GitHub上找到的一个例子。 https://gist.github.com/greyli/addff01c19ddca78cddf386800e57045