在Flas中,将上载的文件保存到磁盘上不起作用

2024-10-01 13:23:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将上传的任何图像存储到static/customlogos文件夹中,名称为“徽标.png“不管它的实际名称是什么。我有一个基本的烧瓶设置与典型的静态和模板文件夹。为了简单起见,我在下面的代码中删除了扩展验证之类的内容。但是,这样做会抛出一个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'))

Tags: thename图像文件夹名称pngsave静态
2条回答

您可以简化如下操作:

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)

注意:确保您已经在static文件夹中创建了customlogos。在

显然,您希望将上载的文件另存为static/customlogos/logo.png,这是相对于Flask应用程序目录的路径,但是您已经指定了绝对不存在的路径/static/customlogos
此外,根据您的评论,您是在Windows下开发的,这增加了您的问题的不一致性。在

无论如何,要实现您想要的,您需要知道应用程序的绝对路径,并将其作为起点:

latestfile.save(os.path.join(app.root_path, 'static/customlogos/logo.png'))

跨平台变型:

^{pr2}$

忍者防尘变型:

latestfile.save(os.path.join(app.root_path, app.config['STATIC_FOLDER'], 'customlogos', 'logo.png'))

相关问题 更多 >