Home > OS >  How can I restrict file types and make my code more secure?
How can I restrict file types and make my code more secure?

Time:06-20

I'm brand new to Flask and attempting to make a secure file upload web app. I want to limit the file types that can be uploaded and specifically block scripting languages.

My app.py code:

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)

And my upload-file.html code:

{{msg}}
<br>
<form action="/" method="POST" enctype="multipart/form-data">
    <input  type="file" name="file_name" multiple>
    <input type="submit" value="Submit">
</form>

CodePudding user response:

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in 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.

if allowed_file(f.filename):
    f.save(os.path.join(app.config['UPLOAD_PATH'], f.filename))
    return render_template("upload-file.html", msg="File has been successfully uploaded")
else:
    return render_template("upload-file.html", msg="File extension not allowed")

CodePudding user response:

You can get help from this doc.

https://flask.palletsprojects.com/en/2.1.x/patterns/fileuploads/

  • Related