在Flask中保存上传只保存到项目根目录 [英] Saving upload in Flask only saves to project root
问题描述
当我上传一个新文件时,即使我指定了一个不同的 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)))
最好将本地数据存储在实例文件夹中,而不是项目根目录。烧瓶已经知道那里了。请确保您先创建实例
目录。
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.
f.save(os.path.join(app.instance_path, 'htmlfi', secure_filename(f.filename)))
这篇关于在Flask中保存上传只保存到项目根目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!