我一直在尝试使用Flask和HTML表单上传文件。现在我可以保存上传的文件,但它显示为空(0字节)。之后,我将表单条目存储在数据库中。
所以我坚持保存文件。 这是python代码
@app.route('/handle_data', methods=['POST'])
def handle_data():
naam = request.form['naam']
leeftijd = request.form['leeftijd']
gewicht = request.form['gewicht']
geslacht = request.form['geslacht']
filename = "x"
if request.method == 'POST' and 'photo' in request.files:
filename = photos.save(request.files['photo'])
photos.save(request.files['photo'], opslag)
cur = mysql.connect()
cursor = cur.cursor()
cursor.execute("INSERT INTO gekko (naam, leeftijd, gewicht, geslacht, foto) VALUES (%s, %s, %s, %s, %s)", (naam, leeftijd, gewicht, geslacht, filename))
# cursor.execute("INSERT INTO gekko (naam, leeftijd, gewicht) VALUES (" + str(naam) + "," + leeftijd + "," + gewicht + ")")
cur.commit()
cursor.close()
cur.close()
return "added"
HTML表单:
{% extends "base.html" %}
{% block body %}
<form action="{{ url_for('handle_data') }}" enctype=multipart/form-data
method="POST">
Naam van de gekko:<br>
<input type="text" name="naam">
<br>
Leeftijd van de gekko:<br>
<input type="text" name="leeftijd">
<br>
Gewicht van de gekko:<br>
<input type="text" name="gewicht">
<br>
Geslacht van de gekko:<br>
<input type="radio" name="geslacht" value="man"> Man
<input type="radio" name="geslacht" value="vrouw"> Vrouw<br>
<br>
<input type="file" id="photo" name="photo">
<br>
<input type="submit" value="Submit">
</form>
{% endblock %}
答案 0 :(得分:0)
我们真的不知道班级photos
是什么,也不知道它的方法save
是做什么的,但这可能是错误发生的地方。
请改为尝试:
request.files['photo'].save('test.jpg')
答案 1 :(得分:0)
我意识到,当您在表单中使用“多个”属性时,flask习惯于包含一个空文件上传,其名称和详细信息与其中一个文件附件(通常是第一个附件)完全相同。
我的解决方法是
一个例子...
# ...
def upload_file(req):
if req.method != 'POST': return
# file with 'multiple' attribute is 'uploads'
files = req.files.getlist("uploads")
# get other single file attachments
if req.files:
for f in req.files: files.append(req.files[f])
for f in files:
if not f.filename: continue
tmp_fname = YOUR_TEMPORARY_FILENAME
while os.path.isfile(tmp_fname):
# you can never rule out the possibility of similar random
# names
tmp_fname = NEW_TEMPORARY_FILENAME
# TEMP_FPATH is he root temporary directory
f.save(os.path.join(TEMP_FPATH, tmp_fname))
# and here comes the trick
if os.stat(os.path.join(TEMP_FPATH, tmp_fname)).st_size:
os.system("mv \"{}\" \"{}\" > /dev/null 2> /dev/null".format(
os.path.join(TEMP_FPATH, tmp_fname),
os.path.join(ACTUAL_FILEPATH, f.filename))
))
else:
# cleanup
os.remove(os.path.join(TEMP_FPATH, tmp_fname))
pass
@app.route("/upload", methods=["POST"])
def upload():
upload_files(request)
return "files are uploaded!"
# ...