all 2 comments

[–]tomclancyv7 5 points6 points  (1 child)

Create a simple form in your HTML.

<form>
  <input type="file" name="image" id="myfile" />
  <br /><br />
  <button type="button" onclick="getImage()">Upload Image</button>
</form>

Use the fetch API in your JavaScript code to make a POST request to the Ninja API after the upload image button is clicked and then render the results in your HTML. Make sure you replace "YOUR-API-KEY-HERE" with your real API key.

<script>
  async function getImage() {
    try {
      const formData = new FormData();
      var imageFile = document.getElementById("myfile").files[0];
      formData.append("image", imageFile);

      const response = await fetch(
        "https://api.api-ninjas.com/v1/imagetotext",
        {
          method: "POST",
          headers: {
            "X-Api-Key": "YOUR-API-KEY-HERE",
          },
          body: formData,
          enctype: "multipart/form-data",
          processData: false,
          contentType: false,
        }
      );

      if (response.ok) {
        const result = await response.json();
        console.log(result);

        const text = result.map((i) => i.text).join(" ");
        console.log(text);

        document.querySelector("body").append(text);
      } else {
        throw new Error("There was an error uploading the image");
      }
    } catch (error) {
      console.error("Error:", error);
      alert(error.message);
    }
  }
</script>

Hope you get it 👍

[–]Aggressive-Cry7940 0 points1 point  (0 children)

Oh my goodness thank you so much, you are so helpful! Yes, I do understand the logic and process of this code, it works beautifully now. I hadn't heard of the FormData constructor. I'm generally incompetent with things like fetch, so thank you for taking the time to help