Title: uploading image to wordpress site with javascript fetch function failed
Last modified: February 18, 2023

---

# uploading image to wordpress site with javascript fetch function failed

 *  [safayet75](https://wordpress.org/support/users/safayet75/)
 * (@safayet75)
 * [3 years, 3 months ago](https://wordpress.org/support/topic/uploading-image-to-wordpress-site-with-javascript-fetch-function-failed/)
 * [[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.
 *     ```wp-block-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();
           })
       ```
   

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

 *  [Albert Bretado](https://wordpress.org/support/users/abretado1985/)
 * (@abretado1985)
 * [3 years, 3 months ago](https://wordpress.org/support/topic/uploading-image-to-wordpress-site-with-javascript-fetch-function-failed/#post-16489896)
    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:
 *     ```wp-block-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](https://wordpress.org/support/users/safayet75/)
 * (@safayet75)
 * [3 years, 3 months ago](https://wordpress.org/support/topic/uploading-image-to-wordpress-site-with-javascript-fetch-function-failed/#post-16490474)
 * Tried with your corrected version, but still uploading failed
 *  [Albert Bretado](https://wordpress.org/support/users/abretado1985/)
 * (@abretado1985)
 * [3 years, 3 months ago](https://wordpress.org/support/topic/uploading-image-to-wordpress-site-with-javascript-fetch-function-failed/#post-16492313)
 * Try this
 *     ```wp-block-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 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.

## Tags

 * [javascript](https://wordpress.org/support/topic-tag/javascript/)
 * [media](https://wordpress.org/support/topic-tag/media/)
 * [upload](https://wordpress.org/support/topic-tag/upload/)

 * In: [Developing with WordPress](https://wordpress.org/support/forum/wp-advanced/)
 * 3 replies
 * 2 participants
 * Last reply from: [Albert Bretado](https://wordpress.org/support/users/abretado1985/)
 * Last activity: [3 years, 3 months ago](https://wordpress.org/support/topic/uploading-image-to-wordpress-site-with-javascript-fetch-function-failed/#post-16492313)
 * Status: not resolved

## Topics

### Topics with no replies

### Non-support topics

### Resolved topics

### Unresolved topics

### All topics
