【问题标题】:File is empty after saving flask uploads保存烧瓶上传后文件为空
【发布时间】:2018-10-16 18:30:58
【问题描述】:

我一直在尝试使用 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 %}

【问题讨论】:

    标签: html flask


    【解决方案1】:

    我们真的不知道photos 是什么类,也不知道save 的方法是什么,但这可能是错误发生的地方。

    试试这个:

    request.files['photo'].save('test.jpg')
    

    【讨论】:

    • 感谢它为我完成了这项工作!
    【解决方案2】:

    我意识到,当您在表单中使用“多个”属性时,Flask 习惯于包含一个与文件附件(通常是第一个附件)完全相同的名称和详细信息的空文件上传。

    我的解决方法是

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

    【讨论】:

      猜你喜欢
      • 2018-12-30
      • 2020-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-30
      • 2021-07-03
      • 2021-08-15
      • 2016-08-30
      相关资源
      最近更新 更多