我正在遵循在Flask中上载文件的确切教程,网址为http://flask.pocoo.org/docs/0.12/patterns/fileuploads/。 代码如下:
import os
from flask import Flask, flash, request, redirect, url_for
from werkzeug.utils import secure_filename
UPLOAD_FOLDER = '/my/file/path/uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/', 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 a 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>
<h1>Upload new File</h1>
<form method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
'''
奇怪的是,这很早就奏效了。我什至可以将其托管在Heroku上,并且可以上传文件。但是现在,我收到以下错误:
2018-07-26T17:28:36.126457+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/werkzeug/datastructures.py", line 2725, in save
2018-07-26T17:28:36.126455+00:00 app[web.1]: File "/app/app2.py", line 33, in upload_file
2018-07-26T17:28:36.126457+00:00 app[web.1]: file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
2018-07-26T17:28:36.126460+00:00 app[web.1]: dst = open(dst, 'wb')
2018-07-26T17:28:36.126515+00:00 app[web.1]: FileNotFoundError: [Errno 2] No such file or directory: '/my/file/path/uploads/file.png'
有人猜测为什么会这样吗?它曾经可以正常工作,但是现在即使Flask开发人员自己提供的代码也无法使用。我检查了很多文件路径,所以我知道问题不存在,并单独测试了os.path.join,并且运行良好。它似乎无法保存,特别是file.save本身存在问题。但是除了file.save的问题之外,我无法弄清楚出了什么问题。 我仍在Heroku上运行它。看来,即使我上传文件并尝试继续执行代码,Heroku也找不到文件/无法访问我的目录?
任何帮助都会很棒!
答案 0 :(得分:0)
我知道了。这是一个heroku问题-heroku文件是远程保存的,我可以通过运行heroku run bash
访问这些文件。执行ls会显示完全不同的文件路径。修复所有内容以匹配该文件路径,而不是我服务器本地的文件路径,即可对其进行修复!