问题
I am working with the flask extension called "flask-uploads" and I only want to allow real pictures to be uploaded (jpg, png so on). How can I restrict the type of uploaded file?
@app.route("/post", methods=["GET", "POST"])
@login_required
def post():
# HERE I'M LINKING TO ANOTHER FILE, THIS IS NOT THE ERROR
post = posts.Post(session["user_id"])
if request.method == "POST" and 'photo' in request.files:
# save photo in img folder
try:
file = photos.save(request.files["photo"])
# I THINK THE ERROR IS IN HERE
except UploadNotAllowed:
return redirect(url_for("index"))
else:
path = 'static/' + str(file)
post.upload(path)
return redirect(url_for("index"))
else:
following = post.loadgroups()
return render_template("post.html", groups = following)
This is the configuration of flask-uploads:
from flask_uploads import UploadSet, IMAGES, configure_uploads, UploadNotAllowed
# configure flask_upload API
photos = UploadSet("photos", IMAGES)
app.config["UPLOADED_PHOTOS_DEST"] = "static/img"
configure_uploads(app, photos)
回答1:
photos = UploadSet("photos", IMAGES)
This line controls only image file can be uploaded. However, if you want to be more specific you can
photos= UploadSet('photos', ('png', 'jpg'))
来源:https://stackoverflow.com/questions/48370533/flask-uploads-define-which-files-are-allowed