首页 > 解决方案 > 如何使用 HTML 表单输入类型文件和烧瓶将图像保存到静态文件夹内的文件夹中

问题描述

在我的烧瓶应用程序中,我希望用户能够将图像上传到静态文件夹内的文件夹 - 称为壁纸。目前我收到一个flask.debughelpers.DebugFilesKeyError,但是我没有看到我正在使用的键有任何错误


我试过的


烧瓶应用程序

@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'))

登录.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>

标签: pythonhtmlformsflask

解决方案


更新您的HTML

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

并加上{wallpaper.filename}引号。


推荐阅读