所以,我一直在尝试将图像上传器添加到我的代码中,但是遇到了问题。尽管我认为我已经正确配置了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/ 来存储文件时,上传程序没有任何问题。我猜测它在寻找我的文件夹时没有找到正确的路径。有人可以帮忙吗?我是一个非常业余的Python开发者。
UPLOAD_FOLDER = './static/uploads/'
,但它返回以下错误:IOError: [Errno 2] No such file or directory: './static/uploads/Bathroom_Kitchen_Home_Decor_Outdoor__More_-_Google_Chrome_2016-06-18_13.32.14.png'
- dizzy/tmp
上正常工作吗?如果是这样,那么应该是路径问题:无论是错误的路径还是错误的权限。在调试过程中,从函数内部打印路径的值,并尝试使用相同的用户访问它。我将编辑我的答案,添加一种更 Pythonic 的方法来获取正确的资源路径。 - kardajIOError: [Errno 2] No such file or directory: '/home/ubuntu/workspace/static/uploads/..IMG_0334.jpg'
现在我只需要在我的工作区内找到正确的文件夹。或者,我该如何将此路径设置为相对路径,以便我可以使用./static
选项? - dizzybasedir = os.path.abspath(os.path.dirname(__file__))
,在测试后没有返回错误!它获取了workspaceurl/uploads/filename,但是却返回了“找不到文件”错误。 - dizzy