rishi
rishi

Reputation: 640

How to save an image into a folder inside the static folder using HTML form input type file and flask

In my flask app I want the user to be able to upload an image to a folder inside the static folder - called wallpaper. Currently I'm receiving a flask.debughelpers.DebugFilesKeyError, however I don't see any error in the keys I'm using


What I've tried


flaskapp.py

@app.route('/changeWallpaper' , methods = ['POST', 'GET'])
def change_home_wallpaper():

    UPLOADS_PATH = join(dirname(realpath(__file__)), 'static\\wallpaper')

    if request.method == "POST":
        wallpaper = request.files['wallpaper']
        if wallpaper.filename != '':
                image = request.files['wallpaper']
                image.save(os.path.join(UPLOADS_PATH, secure_filename(image.filename)))

        cur = db2.cursor()
        sql = f"UPDATE wallpaper set pic = {wallpaper.filename} where sno = 1"
        cur.execute(sql)
        db2.commit()
        cur.close()
        return redirect(url_for('home'))
    else:
        return redirect(url_for('home'))

loggedin.html

<div class="jumbotron">
    <form action="{{url_for('change_home_wallpaper')}}" method="post">
        <div class="container">
            <input type="file" name="wallpaper"/>
            <input type="submit" class="btn btn-primary"/>
        </div>
    </form>

</div>

Upvotes: 0

Views: 1747

Answers (1)

simkusr
simkusr

Reputation: 812

Update your HTML

<form action="/path" method="post" enctype="multipart/form-data">
</form>

and put {wallpaper.filename} in quotes.

Upvotes: 1

Related Questions