簡體   English   中英

使用燒瓶發送文件並返回數據,而無需刷新html頁面

[英]Send file with flask and return a data without refreshing the html page

我正在開發一個Web應用程序,該應用程序將接收灰度輸入並使用機器學習返回該圖像的彩色版本。 為此,Web應用程序帶有一個使用Flask微框架鏈接前端html頁面的python后端。
我正在發送要在python中處理的圖像,然后返回圖像名稱以從其目錄顯示它。 我的問題是如何在不重新加載html頁面的情況下進行先前的操作?

我做了一個最小的工作示例,它確實滿足您的要求:

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()

我不檢查文件擴展名或覆蓋文件,因此您應該進一步保護此功能。 但是這里有基本的基礎架構。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM