Python flask ajax get image - latest EDIT - issue

Since yesterday, I’m trying to understand how I can use a base64 encoded image from a specific view in a different view.

I need to replace my form.company_logo_image_path.data , which is the original image, with a new size that is resizing. The new modified image is sent via AJAX to the new view.

Here is my AJAX:

 var dataurl = canvas.toDataURL("image/png"); $.ajax({ type: "POST", url: "/profil/unternehmen-bearbeiten/resize-image", data:{ a: dataurl } }).done(function() { console.log('sent'); }); 

I created a new view where the image is decoded and stored in the body variable:

 @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 

I tested this by saving the image in a folder on my local machine, and it worked so that the body variable saved the resized image.

Now I need this image to be sent to another view, where it will be uploaded to AWS3, and I will use this image instead of 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) # ... 

The problem here is that I get the Bad Request site if I try to access the results of the resize_image function from the first view. How can I access a new image?


I have been working on this problem since yesterday, and this is the biggest problem I have ever had, here is my old question with my progress: Old question with my progress and attempts

EDIT

It doesn't matter what I try, sending to "/profil/unternehmen-bearbeiten" also results in a bad request error.

Querying data a leads in any case to bad queries:

 try: print request.values['a'] except Exception as e: print "error", e 

The exception here is an invalid request.

Also, requesting the canvas itself leads to bad requests, the console in the browser does not tell me something useful that I can use / understand. Its the same as in the console in Eclipse, it receives 400 Bad Request on the route where I am trying to send:

 try: print request.form['uploading_canvas'] except Exception as e: print "error 1", e 

enter image description here

EDIT

Finally, I made some serious progress! I tried to request data in if form.validate_on_submit(): Now I put the code outside if form.validate_on_submit(): and now I can request the data, I still have problems, but from here I can continue to work!

 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(): # ... 

I get a bad request again, but now I understand why. form.validate_on_submit(): itself is also a POST request, so I need the correct if condition and it will work (I think).

Basically the problem is this: My ajax request and form.validate_on_submit(): on the route I send are like POST requests, so I often get Bad Request so that there is a conflict. I tried to create a custom form checkbox. I tried to move the code and other other conditions. I just do not understand.

My recent attempts:

  """ 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) """ 
+5
source share
1 answer

I think you need a different approach with this, as you seem to mix with all the data passing between the HTML / Flask / Javascript formats.

Basically, your Javascript should fill in the hidden field in your form using the dataURL of the modified canvas image. This will then be passed to your Flask window, where you can upload data to S3.

Below is a simple example application illustrating what I mean.

app.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) 

Templates /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> 
+2
source

Source: https://habr.com/ru/post/1265480/


All Articles