'No response when passing multiple images to Flask with ajax

I got issues when trying to pass input values from HTML to Flask. I used javascript and FormData to pass multiple images to the Flask function.

Here is the HTML:

<form>
   <input
      id="imagesInp"
      type="file"
      name="imagesInp"
      class="input-button"
      onchange="readUrl(this)"
      multiple
   />
</form>
<button name="images-btn" id="imagesbutton" class="submit-detect-btn">Detect</button>

Here is the js part:

$("#imagesbutton").click(() => {
    imagebox = $("#imagebox");
    link = $("#link");
    input = document.getElementById('imagesInp');
    console.log(input.files);
    if (input.files && input.files[0]) {
      var formData = new FormData();
      for (let i = 0; i < input.files.length; i++) {
        formData.append("images", input.files[i]);
      }
      formData.forEach((value, key) => {
        console.log("key %s: value %s", key, value);
      });
      $.ajax({
        url: "/detect-images", // fix this to your liking
        type: "POST",
        data: formData,
        cache: false,
        processData: false,
        contentType: false,
        error: function (data) {
          console.log("upload error", data);
          console.log(data.getAllResponseHeaders());
        },
        success: function (data) {
          console.log(data);
          // $("#detectedimg").attr("src", "/detected/" + encodeURIComponent(data));
          // $("#link").css("visibility", "visible");
          // $("#download").attr("href", "static/images/" + data);
          console.log(data);
        },
      });
    }
  });

Here is Flask:

@app.route("/detect-images", methods=['POST'])
def detect_images():
    if not request.method == "POST":
        return
    images = request.files.getlist('images')
    print(images)
    for img in images:
        img.save(os.path.join(uploads_dir, secure_filename(img.filename)))
        name = img.filename
    return name

I used the same structure when uploading a single image, it worked all right. But here when I click the button, the input images can be passed to formData, they are shown in the console.log. But in the ajax part, the data seems not to be passed to the Flask function. And there are no errors, no /post messages, just like I haven't clicked the button.

Don't mind the return value, I am gonna complete the whole function later, now I just wanna make sure the data can be uploaded to the directory correctly.

Thanks so much if you could help me!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source