Norstorin
Norstorin

Reputation: 71

flask jquery html form returning None for Image

New to web development, and trying to do a simple upload of an image, the goal is to get in in s3. But currently When i select a photo and submit the request comes back as none, cant figure out why.

html form

<form name="update_profile_image_form" id="update_profile_image_form" class="text-center mt-2" method="POST" enctype="multipart/form-data" style="display: block;" action="/user/update/profile-image/">
  <input type="file" class="form-control-file form-control-file-sm ml-3 mt-2" id="profile_image" name="profile_image" accept="image/*">
  <input type="submit" value="Update" class="form-control-file form-control-file-sm ml-2 mt-2 text-center btn btn-sm btn-info" style="width: 90%;"></input>
</form>

script

$("form[name=update_profile_image_form").submit(function(e) {

  var $form = $(this);
  var $error = $form.find(".error");
  var data = $form.serialize();

  $.ajax({
      url: "/user/update/profile_image",
      type: "POST",
      data: data,
      dataType: "json",
      success: function(resp) {
        window.location.href = "/account/";
        
      }
    });
  
    e.preventDefault();
  });

route

@app.route('/user/update/profile_image', methods=['POST'])
def update_profile_image(): 
  return User().update_profile_image()

function

  def update_profile_image(self):
    img = request.files.get('profile_image')
    print(img)
    
    return redirect(url_for('account'))

also tried img = request.form.get('profile_image')

No Error, the print(img) comes back as none

the goal is to upload the image, pass to the function, assign it a uuid and upload to s3, Thank you all in advance!

Upvotes: 0

Views: 232

Answers (1)

dancingCamel
dancingCamel

Reputation: 181

You cannot serialize an image and send it as json.

You should use a form data object. However, print(img) will not work as you cannot print an image in this way.

Alternatively you could pass the image as a string by converting it to base64.

Upvotes: 1

Related Questions