如何限制文件类型并使我的代码更安全?
我是全新的烧瓶,并试图制作一个安全的文件上传Web应用程序。我想限制可以上传并专门阻止脚本语言的文件类型。
我的app.py代码:
from flask import Flask, render_template, request, current_app, abort
import os
app = Flask(__name__)
app.config["UPLOAD_PATH"] = "Desktop"
app.config['UPLOAD_EXTENSIONS'] = ['.jpg', '.png', '.gif']
app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024
@app.route("/",methods=["GET","POST"])
def upload_file():
if request.method == "POST":
f = request.files['file_name']
f.save(os.path.join(app.config['UPLOAD_PATH'], f.filename))
return render_template("upload-file.html", msg="File has been successfully uploaded")
return render_template("upload-file.html", msg="Please Choose a File")
if __name__ == "__main__":
app.run(debug=True)
以及我的upload-file.html代码:
{{msg}}
<br>
<form action="/" method="POST" enctype="multipart/form-data">
<input type="file" name="file_name" multiple>
<input type="submit" value="Submit">
</form>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以从此文档获得帮助。
You can get help from this doc.
https://flask.palletsprojects.com/en/2.1.x/patterns/fileuploads/
将文件名传递给此功能,它将返回true app.config ['upload_extensions']中的文件扩展名。
如果语句,您可以将代码放在
中。
pass the file name to this function it will return True the file extension in your app.config['UPLOAD_EXTENSIONS'].
And you can put your code in an
if
statement.