将上传的文件保存到磁盘在Flask中不起作用 [英] Saving an uploaded file to disk doesn't work in Flask
问题描述
无论实际名称是什么,我都希望将任何上传的图像以"logo.png"的名称存储到static/customlogos文件夹中.我有基本的Flask设置,其中包含典型的静态和模板文件夹.为简单起见,我在下面的代码中删除了扩展验证之类的内容.但是,这样做会引发FileNotFound错误.由于我想在各种环境中运行我的应用程序,因此我不想使用静态路径.我究竟做错了什么?感谢您的帮助.
I want to store any uploaded image to the static/customlogos folder with the name "logo.png" no matter what its actual name is. I have a basic Flask setup with the typical static and template folders. For simplicity I removed things like extension validation in my code below. However doing it like this throws a FileNotFound error. Since I want to run my app on various environments, I don't want to use a static path. What am I doing wrong? Thanks for your help.
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'))
推荐答案
显然,您要将上载的文件另存为 static/customlogos/logo.png
,这是与Flask应用程序目录相关的路径,但您已指定绝对不存在的路径/static/customlogos
.
此外,根据您的评论,您正在Windows下进行开发,这会增加问题的不一致性.
Obviously, you want to save uploaded file as static/customlogos/logo.png
, path that is relative to your Flask application directory, but you have specified the absolute non-existing path /static/customlogos
.
Furthermore, according to your comments you are developing under Windows, which adds inconsistency to your question.
无论如何,要实现所需的功能,您需要知道应用程序的绝对路径,并将其用作起点:
In any case, to achieve what you want, you need to know the absolute path of your application, and use it as a starting point:
latestfile.save(os.path.join(app.root_path, 'static/customlogos/logo.png'))
跨平台版本:
latestfile.save(os.path.join(app.root_path, 'static', 'customlogos', 'logo.png'))
忍者防尘版:
latestfile.save(os.path.join(app.root_path, app.config['STATIC_FOLDER'], 'customlogos', 'logo.png'))
这篇关于将上传的文件保存到磁盘在Flask中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!