gpt4 book ai didi

python - Flask-上传 IOError : [Errno 2] No such file or directory

转载 作者:太空宇宙 更新时间:2023-11-03 12:45:29 24 4
gpt4 key购买 nike

所以,我一直在尝试向我的代码中添加一个图像 uploader ,但我一直遇到问题。尽管我认为我的 upload_folder 配置正确,但我不断收到如下错误:IOError: [Errno 2] No such file or directory: '/static/uploads/compressor.jpg' 即使文件/目录存在。

代码如下:

在config.py中

UPLOAD_FOLDER = 'static/uploads'

init.py中
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

在 views.py 中

@app.route('/fileupload', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
#check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also
#submit an empty part without filename
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('uploaded_file',
filename=filename))
return '''
<!doctype html>
<title>Upload new File</title>
<h>UPload new file</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
'''

@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename)

我的文件夹结构如下

  /project folder
--/app
----/static
--------/uploads
----/templates
----_init__.py
----views.py
--config.py

当我使用/tmp/将其存储在内存中时, uploader 可以正常工作。我假设它没有在寻找我的文件夹的正确路径。有人可以帮忙吗?我是一个非常业余的 Python 开发人员。

最佳答案

/tmp/static/uploads/.. 都是绝对路径。并且您的代码在 / 文件夹中查找,而不是在您项目的文件夹中查找。您应该使用绝对路径指向您的文件夹 /path/to/your/project/static/uploads/.. 或使用相对于正在执行的代码的路径,例如 ./静态/上传

您还可以使用以下代码片段生成绝对路径:

from os.path import join, dirname, realpath

UPLOADS_PATH = join(dirname(realpath(__file__)), 'static/uploads/..')

关于python - Flask-上传 IOError : [Errno 2] No such file or directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37901716/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com