我想将任何上传的图像存储到名为“logo.png”的static / customlogos文件夹中,无论其实际名称是什么。我有一个基本的Flask设置,包含典型的静态和模板文件夹。为简单起见,我在下面的代码中删除了扩展验证等内容。但是这样做会抛出FileNotFound错误。由于我想在各种环境中运行我的应用程序,我不想使用静态路径。我究竟做错了什么?谢谢你的帮助。
latestfile = request.files['customlogo']
#This prints the file name of the uploaded file
print(latestfile.filename)
#I want to save the uploaded file as logo.png. No matter what the uploaded file name was.
latestfile.save(os.path.join('/static/customlogos', 'logo.png'))
答案 0 :(得分:3)
显然,您希望将上传的文件保存为static/customlogos/logo.png
,相对于Flask应用程序目录的路径,但您已指定绝对不存在的路径/static/customlogos
。
此外,根据您在Windows下开发的评论,这会增加您的问题的不一致性。
在任何情况下,要实现您想要的,您需要知道应用程序的绝对路径,并将其作为起点:
latestfile.save(os.path.join(app.root_path, 'static/customlogos/logo.png'))
跨平台变体:
latestfile.save(os.path.join(app.root_path, 'static', 'customlogos', 'logo.png'))
Ninja防尘变体:
latestfile.save(os.path.join(app.root_path, app.config['STATIC_FOLDER'], 'customlogos', 'logo.png'))
答案 1 :(得分:1)
您可以简化操作,如下所示:
from flask import Flask, request, session, g, redirect
from flask import url_for, abort, render_template, flash, jsonify
import os
# Create two constant. They direct to the app root folder and logo upload folder
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLDER = os.path.join(APP_ROOT, 'static', 'customlogos')
# Configure Flask app and the logo upload folder
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# In controller save the file with desired name
latestfile = request.files['customlogo']
full_filename = os.path.join(app.config['UPLOAD_FOLDER'], 'logo.png')
latestfile.save(full_filename)
N.B。:确保您已在customlogos
文件夹中创建static
。