因此,我一直在尝试将图像上传器添加到我的代码中,但是却遇到了问题。即使我以为自己正确配置了upload_folder
,即使文件/目录存在,我仍然会收到类似IOError: [Errno 2] No such file or directory: '/static/uploads/compressor.jpg'
的错误。
这是代码:
在config.py中
UPLOAD_FOLDER = 'static/uploads'
在中初始化 .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/将其存储在内存中时,上传器将正常工作。我认为它不在我的文件夹的正确路径中。有人可以帮忙吗?我是一个非常业余的python开发人员。
最佳答案
/tmp
和/static/uploads/..
都是绝对路径。您的代码正在/
文件夹中查找,而不是在项目的文件夹中查找。您应该使用绝对路径指向文件夹/path/to/your/project/static/uploads/..
或使用相对于正在执行的代码(例如./static/uploads
)的路径。
您还可以使用以下代码段生成绝对路径:
from os.path import join, dirname, realpath
UPLOADS_PATH = join(dirname(realpath(__file__)), 'static/uploads/..')
关于python - Flask-Uploads IOError : [Errno 2] No such file or directory,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37901716/