我正在开发一个Web应用程序,它使用灰度输入并使用机器学习返回该图像的彩色版本。为此,Web应用程序使用python后端使用Flask微框架链接前端html页面。
我正在发送我选择在python中处理的图像,然后返回图像名称以从其目录中显示它。我的问题是如何在不重新加载html页面的情况下完成之前的操作?
答案 0 :(得分: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()
我没有检查文件扩展名或覆盖文件,因此您应该更多地保护此功能。但基础设施就在那里。