Rom*_*man 5 python ajax image flask
从昨天开始,我试图了解如何在其他视图中使用特定视图中的编码base64图像.
我需要用form.company_logo_image_path.data调整大小的新图像替换原来的图像.新调整大小的图像通过AJAX发送到新视图.
这是我的AJAX:
var dataurl = canvas.toDataURL("image/png");
$.ajax({
type: "POST",
url: "/profil/unternehmen-bearbeiten/resize-image",
data:{
a: dataurl
}
}).done(function() {
console.log('sent');
});
Run Code Online (Sandbox Code Playgroud)
我创建了一个新视图,其中图像被解码并存储在body变量中:
@app.route('/profil/unternehmen-bearbeiten/resize-image', methods=["POST"])
def resize_image():
data_url = request.values['a']
content = data_url.split(';')[1]
image_encoded = content.split(',')[1]
body = base64.decodestring(image_encoded.encode('utf-8'))
return body
Run Code Online (Sandbox Code Playgroud)
我通过将图像保存到本地计算机上的文件夹来测试它,并且它可以正常工作,因此body变量可以正确存储调整大小的图像.
现在我需要将此图像发送到其他视图,然后将其上传到AWS3,我将使用此图像而不是form.company_logo_image_path.data:
@app.route('/profil/unternehmen-bearbeiten', methods=["GET", "POST"])
@login_required
@check_confirmed
def edit_company():
the_company = Company.query.filter_by(users_id=current_user.id).first()
form = EditCompanyForm(obj=the_company)
used_file = the_company.company_logo_image_path
if form.validate_on_submit():
form.populate_obj(the_company)
imagedata = resize_image()
print "The", imagedata
if form.company_logo_image_path.data:
upload_image_to_aws('baubedarf', "userimages/", form.company_logo_image_path, the_company,'company_logo_image_path', the_company.company_name)
# ...
Run Code Online (Sandbox Code Playgroud)
这里的问题是,Bad Request如果我尝试resize_image从第一个视图访问该函数的结果,我会得到一个站点.如何访问新图像?
我从昨天开始研究这个问题,这是迄今为止我遇到过的最大问题,这是我对进步的一个老问题: 我的进步和尝试的老问题
编辑
无论我尝试什么,发送"/profil/unternehmen-bearbeiten"也会导致错误的请求错误.
在a任何地方请求数据都会导致错误的请求:
try:
print request.values['a']
except Exception as e:
print "error", e
Run Code Online (Sandbox Code Playgroud)
这里的例外是错误请求
同时请求画布本身会导致错误的请求,浏览器中的控制台并没有告诉我一些有用的东西,我可以使用/理解.它与Eclipse中的控制台相同,它在我尝试发送到的路径中获得400 Bad Request:
try:
print request.form['uploading_canvas']
except Exception as e:
print "error 1", e
Run Code Online (Sandbox Code Playgroud)
编辑
最后我取得了一些重大进展!我试图请求数据if form.validate_on_submit():.我现在把代码放在外面if form.validate_on_submit():,我现在可以请求数据,我仍然遇到问题,但是从这里我可以继续工作!
if request.method == 'POST':
print "post"
file_data = request.values['a']
imagedata = resize_image(file_data)
print "The", type(imagedata)
if form.validate_on_submit():
# ...
Run Code Online (Sandbox Code Playgroud)
我在这里再次提出错误请求,但我现在明白为什么.form.validate_on_submit():本身也是一个POST请求,所以我需要正确的if条件,它会工作(我猜).
基本上问题是:我的ajax请求和form.validate_on_submit():我发送到的路由都是POST请求,这就是为什么我经常收到错误请求,存在冲突.我正在尝试创建自定义表单复选框.我正在尝试移动代码和其他不同的条件.我根本得不到它.
我最近的尝试:
"""
if form.company_check_it.data == True:
print "post 1"
file_data = request.values['a']
imagedata = resize_image(file_data)
print "The", type(imagedata)
else:
print "post 3"
"""
"""
if request.method == 'POST':
print "post"
file_data = request.values['a']
imagedata = resize_image(file_data)
print "The", type(imagedata)
"""
if form.validate_on_submit():
print "post 2"
"""
if form.company_check_it.data == True:
print "post 1"
file_data = request.values['a']
imagedata = resize_image(file_data)
print "The", type(imagedata)
else:
print "post 3"
"""
if request.method == 'POST':
print "post"
file_data = request.values['a']
imagedata = resize_image(file_data)
print "The", type(imagedata)
form.populate_obj(the_company)
"""
data_url = request.values['a']
print data_url
content = data_url.split(';')[1]
image_encoded = content.split(',')[1]
body = base64.decodestring(image_encoded.encode('utf-8'))
print type(body)
"""
Run Code Online (Sandbox Code Playgroud)
我认为你需要一种不同的方法,因为你似乎混淆了 HTML 表单/Flask 视图/Javascript 之间传递的所有数据。
基本上,您的 Javascript 应该使用画布中调整大小的图像的 dataURL 填充表单中的隐藏字段。然后,该数据将提交到您的 Flask 视图,您可以在其中将数据上传到 S3。
下面是一个简单的示例应用程序,说明了我的意思。
应用程序.py
from flask import Flask, url_for, redirect, render_template
from flask_wtf import Form
from wtforms import HiddenField
import base64
class EditCompanyForm(Form):
resized_image = HiddenField()
app = Flask(__name__)
app.config['SECRET_KEY'] = '1234'
@app.route("/", methods=['GET', 'POST'])
def index():
form = EditCompanyForm()
if form.validate_on_submit():
if form.resized_image.data:
data = resize(form.resized_image.data)
print("Uploading to AWS")
# upload_image_to_aws(data, other_variables_as_needed)
return redirect(url_for('index'))
return render_template('index.html', form=form)
def resize(data_url):
content = data_url.split(';')[1]
image_encoded = content.split(',')[1]
body = base64.decodestring(image_encoded.encode('utf-8'))
return body
if __name__ == "__main__":
app.run(debug=True)
Run Code Online (Sandbox Code Playgroud)
模板/index.html
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, 69, 50);
};
imageObj.src = '{{ url_for('static', filename='darth-vader.jpg') }}';
$("#submit").click(function() {
var dataurl = canvas.toDataURL("image/png");
$("#resized_image").val(dataurl);
});
});
</script>
</head>
<body>
<canvas id="myCanvas" width="578" height="400"></canvas>
<form method="post">
{{ form.hidden_tag() }}
<input type="submit" value="Save" id="submit" name="submit" />
</form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)