在 Flask 中保存上传仅保存到项目根目录 [英] Saving upload in Flask only saves to project root

查看:19
本文介绍了在 Flask 中保存上传仅保存到项目根目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我上传新文件时,它会保存到应用程序根文件夹中,即使我指定了不同的 UPLOAD_FOLDER.为什么配置不起作用?

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?

views.py:

from flask import render_template
from flask import request, redirect, url_for,flash
from werkzeug.utils import secure_filename
from app import app
import os

APP_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLD = '/Users/blabla/Desktop/kenetelli/htmlfi'
UPLOAD_FOLDER = os.path.join(APP_ROOT, UPLOAD_FOLD)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/')
def tmrf():
    return render_template('main.html')


@app.route('/uploader', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        f = request.files['file']
        f.save(secure_filename(f.filename))
    return 'file uploaded successfully'

__init__.py:

from flask import Flask

UPLOAD_FOLDER = ''
ALLOWED_EXTENSIONS = set('*.doc')

app = Flask(__name__)
app.config.from_object('config')
from app import views

推荐答案

UPLOAD_FOLDER 不是 Flask 识别的配置选项.f.save 相对于当前工作目录工作,该目录通常是开发过程中的项目根目录.

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

<小时>

最好将本地数据存储在实例文件夹,而不是项目根目录.Flask 已经知道那在哪里.只需确保先创建 instance 目录.


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

<小时>

无论您决定将其保存在何处,您都需要确保运行该应用程序的用户对该目录具有写入权限.如果在使用 mod_wsgi 运行时出现权限错误,例如,用户通常是 httpdwww-data.如果您收到权限被拒绝错误,请检查.


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.

这篇关于在 Flask 中保存上传仅保存到项目根目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆