所以,我一直在尝试将图像上传器添加到我的代码中,但我遇到了问题。即使我认为我的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 开发者。