【问题标题】:Send file with flask and return a data without refreshing the html page用flask发送文件并返回数据而不刷新html页面
【发布时间】:2018-04-27 19:34:59
【问题描述】:

我正在开发一个 Web 应用程序,它接受灰度输入并使用机器学习返回该图像的彩色版本。为此,该网络应用程序带有一个 python 后端,该后端使用 Flask 微框架链接前端 html 页面。
我正在发送我选择在 python 中处理的图像,然后返回图像名称以从其目录中显示它。我的问题是如何在不重新加载 html 页面的情况下进行之前的操作?

【问题讨论】:

    标签: javascript jquery html ajax flask


    【解决方案1】:

    我做了一个最小的工作示例,它完全符合您的要求:

    from flask import Flask, render_template_string, request, jsonify, url_for
    import os
    from werkzeug.utils import secure_filename
    
    if not os.path.isdir("/static"):  # just for this example
        os.makedirs("/static")
    
    app = Flask(__name__)
    
    
    @app.route('/', methods=['GET', 'POST'])
    def index():
        if request.method == 'POST':
            file = request.files['file']
            fname = secure_filename(file.filename)
            file.save('static/' + fname)
            # do the processing here and save the new file in static/
            fname_after_processing = fname
            return jsonify({'result_image_location': url_for('static', filename=fname_after_processing)})
    
        return render_template_string('''
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>title</title>
    </head>
    <body>
    <form enctype="multipart/form-data" method="post" name="fileinfo">
      <label>Some user provided information</label>
      <input type="text" name="some_info" size="12" maxlength="32" /><br />
      <label>File to upload:</label>
      <input type="file" name="file" required />
      <input type="submit" value="Upload the file!" />
    </form>
    <img id="resultimg" scr="">
    <div></div>
    <script>
    var form = document.forms.namedItem("fileinfo");
    form.addEventListener('submit', function(ev) {
      var oData = new FormData(form);
      var oReq = new XMLHttpRequest();
      oReq.open("POST", "{{url_for('index')}}", true);
      oReq.onload = function(oEvent) {
        if (oReq.status == 200) {
          document.getElementById('resultimg').setAttribute('src', JSON.parse(oReq.responseText).result_image_location);
        } else {
          alert("Error " + oReq.status + " occurred when trying to upload your file")
        }
      };
      oReq.send(oData);
      ev.preventDefault();
    }, false);
    </script>
    </body>
    </html>
    ''')
    
    
    app.run()
    

    我不会检查文件扩展名或覆盖文件,因此您应该更加保护此功能。但是基本的基础设施就在那里。

    【讨论】:

    • 各位大佬,非常感谢 :D ,就一个问题,'oReq.status == 200'有什么用
    • 它检查服务器(flask)是否发送了正确的响应。见this link
    • 再次感谢您:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多