一尘不染

在Flask中保存上传仅保存到项目根目录

flask

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

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

阅读 710

收藏
2020-04-05

共1个答案

一尘不染

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

将安全的文件名加入上载文件夹,然后保存到该路径。

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

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

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。如果出现权限被拒绝错误,请检查。

2020-04-05