• I tried to turn an html div element into an png image than I want upload this image in my wordpress site . I wrote following codes, But it is showing image upload failed. Can You find where is wrong. Any help to correct this code appreciated.

    // Capture the div element as a PNG image
      function convertDivToImage() {
     html2canvas(document.querySelector("#wgr")).then(canvas => {
     const imageData = canvas.toDataURL("image/png");
     // Set the Content-Type header
      let headers = new Headers();
      headers.append("Content-Type", "image/png");
      // Set the authorization header
      const authHeader = "Basic " + btoa("username:password");
      // Upload the image to the WordPress site using the REST API
      return fetch("/wp-json/wp/v2/media", {
        method: "POST",
         headers: {
    "Content-Type": "image/png",
    "Authorization": authHeader}, body: JSON.stringify({
          file: imageData,
          "Content-Disposition": attachment; filename="wgr_image.png"
        })
      })
        .then(response => {
          if (!response.ok) {
            throw new Error("Failed to upload image");
          }
          return response.json();
        })
Viewing 3 replies - 1 through 3 (of 3 total)
    1. The Content-Disposition header is not properly formatted. It should be enclosed in quotes and the filename parameter should be preceded by “filename=”.
    2. The fetch function does not handle errors in case the upload fails.

    Here is the corrected code:

    // Capture the div element as a PNG image
    function convertDivToImage() {
      html2canvas(document.querySelector("#wgr")).then(canvas => {
        const imageData = canvas.toDataURL("image/png");
        // Set the Content-Type header
        let headers = new Headers();
        headers.append("Content-Type", "image/png");
        // Set the authorization header
        const authHeader = "Basic " + btoa("username:password");
        // Upload the image to the WordPress site using the REST API
        return fetch("/wp-json/wp/v2/media", {
          method: "POST",
          headers: {
            "Content-Type": "image/png",
            "Authorization": authHeader
          },
          body: JSON.stringify({
            file: imageData,
            "Content-Disposition": 'attachment; filename="wgr_image.png"'
          })
        }).then(response => {
          if (!response.ok) {
            throw new Error("Failed to upload image");
          }
          return response.json();
        }).catch(error => {
          console.error("Error uploading image: ", error);
        });
      });
    }
    
    Thread Starter safayet75

    (@safayet75)

    Tried with your corrected version, but still uploading failed

    Try this

    // Capture the div element as a PNG image
    function convertDivToImage() {
      html2canvas(document.querySelector("#wgr")).then(canvas => {
        const imageData = canvas.toDataURL("image/png");
        // Set the headers
        let headers = new Headers();
        const authHeader = "Basic " + btoa("username:password");
        headers.append("Authorization", authHeader);
        // Upload the image to the WordPress site using the REST API
        return fetch("https://example.com/wp-json/wp/v2/media", {
          method: "POST",
          headers: headers,
          body: imageData
        }).then(response => {
          if (!response.ok) {
            throw new Error("Failed to upload image");
          }
          // Handle the response
          return response.json().then(data => {
            console.log("Image uploaded:", data);
          });
        }).catch(error => {
          console.error("Error uploading image: ", error);
        });
      });
    }
    

    Note that you should replace https://example.com with the actual URL of your WordPress site, and replace username and password with the appropriate credentials for your site.

Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘uploading image to wordpress site with javascript fetch function failed’ is closed to new replies.