Saving upload in Flask only saves to project root

前端 未结 1 686
醉酒成梦
醉酒成梦 2020-11-27 06:57

When I upload a new file, it saves to the application root folder, even though I specified a different UPLOAD_FOLDER. Why doesn\'t the config work?

相关标签:
1条回答
  • 2020-11-27 07:03

    UPLOAD_FOLDER is not a configuration option recognized by Flask. f.save works relative to the current working directory, which is typically the project root during development.

    Join the secured filename to the upload folder, then save to that path.

    f.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename)))
    

    It's better to store local data in the instance folder, not the project root. Flask already knows where that is. Just make sure you create the instance directory first.

    import os
    from werkzeug.utils import secure_filename
    
    # create the folders when setting up your app
    os.makedirs(os.path.join(app.instance_path, 'htmlfi'), exist_ok=True)
    
    # when saving the file
    f.save(os.path.join(app.instance_path, 'htmlfi', secure_filename(f.filename)))
    

    No matter where you decide to save it, you need to make sure the user running the application has write permission to that directory. If you get permission errors when running with mod_wsgi, for example, the user is commonly httpd or www-data. If you get a permission denied error, check that.

    0 讨论(0)
提交回复
热议问题