Flask-uploads define which files are allowed

浪子不回头ぞ 提交于 2019-12-23 05:32:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!