0

I am new to web development and have a small web app where I need a user to upload a cropped image. My issue is that I cannot fetch the image that is send in the jQuery post request.

My Javascript and HTML looks like this:

function sendImage(imageData) {
 var info = {}
 info.upload = imageData
 info.gender = gender.value
 info.ageGroup = ageGroup.value
 
 $.ajax({
   type: "POST",
   url: "/uploadToS3",
   data: info,
   enctype: 'multipart/form-data',
   dataType: "json",
   success: console.log("image written")
 });
}
 <div class="image-editor">
      <input type="file" class="cropit-image-input">
      <div class="cropit-preview"></div>
      <div class="image-size-label">
        Resize image
    </div>
      <input type="range" class="cropit-image-zoom-input">
      <button class="export">Export</button>
</div>

Here is the python code handling the post request

@app.route('/uploadToS3', methods = ['POST'])
def uploadToS3():
    username = session.get('username')
    image = request.files.get('upload')
    gender = request.form['gender']
    ageGroup = request.form['ageGroup']
    fileName = getNewFileName()
    print(image)
    return redirect('/')

image prints as 'None', the issue seems to be in the line where I request the upload parameter. The data being posted to Flask (taken from the form data) is upload:data:image/png;base64 and a very long string. So it looks like it posting correctly.

Any hints would be greatly appreciated

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
NicolaiF
  • 1,283
  • 1
  • 20
  • 44

1 Answers1

0

According to the answers to this question you can't just use an simple object as data when passing files.

For that purpose you have to do the following:

var formData = new FormData();
formData.append("gender",gender.value); // And so on...
formData.append("upload",$("#file")[0].files[0]); // When your file input has id="file"

$.ajax({
  type: "POST",
  url: "/uploadToS3",
  data: formData,
  enctype: 'multipart/form-data',
  // And so on...
});
Siphalor
  • 712
  • 5
  • 16