保存烧瓶上传后文件为空 [英] File is empty after saving flask uploads

查看:57
本文介绍了保存烧瓶上传后文件为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用Flask和HTML表单上传文件.现在,我可以保存上传的文件,但显示为空(0字节).之后,我将表单条目存储在数据库中.

I've been trying to upload a file using Flask and HTML forms. Now I can save an uploaded file but it shows up empty (0 bytes). After that I store the form entries in a database.

所以我坚持保存文件. 这是python代码

So im stuck at saving the file. This is the python code

@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 %}

推荐答案

我意识到flask习惯于包含一个空文件上传,其名称和详细信息与文件附件之一(通常是第一个附件)的名称和详细信息完全相同您可以在表单中使用'multiple'属性.

I realized that flask has a habit of including one empty file upload with the exact same name and details as one of the file attachments(usually the first attachment) WHEN you use the 'multiple' attribute in your form.

我的解决方法是

  1. 创建一个临时的随机文件名并保存文件上传
  2. 使用os.stat(temp_filename).st_size检查文件是否为空
  3. 如果文件为空,请使用os.remove将其删除,否则,将文件重命名为您首选的[安全]文件名

一个例子...

# ...

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!"

# ...

这篇关于保存烧瓶上传后文件为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆