'Unable to send a Base 64 image to Woocommerce /product API with JS

I am actually trying to make a 3D product configurator with verge 3D and have to create new WooCommerce products for every specific product configuration.

Everything seem to work fine and I managed to generate an image capture stored in a variable as base 64 jpeg

I now want to post this variable to /wp-json/wc/v2/products/ with the rest of my product creation query but the API return "Invalid URL Provided."

I fear that the WooCommerce Product REST API can't handle base64 images as img -> src: however some people seem to have managed to pass similar requests.

I included below my JSON code, maybe there is a problem with the formatting...

{
"name": "Config Plexi",
"type": "simple",
"regular_price": "21.99",
"dimensions": {
    "length": "300",
    "width": "300"
},
"description": "Pellentesque habitant morbi tristique",
"images": [
{   "src":"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAoHBwgHBgoICAgLCgoLDhgQDg0NDh0VFhEYIx8lJCIfIiEmKzcvJik0KSEiMEExNDk7Pj4+JS5ESUM8SDc9Pjv/2wBDAQoLCw4NDhwQEBw7KCIoOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozv/wAARCAIyAjIDASIAAhEBAxEB/8QAGAABAQEBAQAAAAAAAAAAAAAAAAECAwf/xAAdEAEBAQEBAQADAQAAAAAAAAAAEQExUQISIXFB/8QAFwEBAQEBAAAAAAAAAAAAAAAAAAEDBP/EABURAQEAAAAAAAAAAAAAAAAAAAAR/9oADAMBAAIRAxEAPwD0oBs5QAAAAUBBQEFARQAAAIAEAAAAFAQUBBQEFAQUBBQEFgCCwBBQEFAQUBBYAgqAAAEAAAAAEFAQUBBSAgoCCoAAAAAACkAAAAAAUBBQEFACAABAAiggoCCgIKAhFICEWEBFAEIoCQigINICEUARQEFASEUgJBYAgoCCgIKAgqABACEAEFAQUBBSAgAAAAAIKAKAAAARQQUBCKQAIACgqEUgIKAiqAgpAQigILAEGgGRqEBlYsICQigILCAhFgCRI0QGRqEBmDUAZFICQigILCAiNAMigJBYAgoCCoIgsAQUBBUgAQAiKAgoCgQA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AACgAAgDAAgAAAAAAAAAAqANCKCiKCgAAAAAAAAAAAAAAAAAAgKCAoAAAAAAAAAAAAAAAAAoAAAAIUFEAAAABAAGAAAAAAAAAAAAAAUAFABQBVAAAEAAAARQBFAEABUAAAD/ABQAABFAAAAAAAEUBUUAAAAAEAAAQAAAAAAAAAB//9k="
    }
]

}

If the functionality mentioned above is not available, I think I will have to use an external PHP file as my configurator code is entirely written in JS

I found the code below but I now need a function to send my base 64 image to the PHP function and retrieve the generated URL to include it in my JSON request

/**
 * Save the image on the server.
 */
function save_image( $base64_img, $title ) {

    // Upload dir.
    $upload_dir  = wp_upload_dir();
    $upload_path = str_replace( '/', DIRECTORY_SEPARATOR, $upload_dir['path'] ) . DIRECTORY_SEPARATOR;

    $img             = str_replace( 'data:image/jpeg;base64,', '', $base64_img );
    $img             = str_replace( ' ', '+', $img );
    $decoded         = base64_decode( $img );
    $filename        = $title . '.jpeg';
    $file_type       = 'image/jpeg';
    $hashed_filename = md5( $filename . microtime() ) . '_' . $filename;

    // Save the image in the uploads directory.
    $upload_file = file_put_contents( $upload_path . $hashed_filename, $decoded );

    $attachment = array(
        'post_mime_type' => $file_type,
        'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $hashed_filename ) ),
        'post_content'   => '',
        'post_status'    => 'inherit',
        'guid'           => $upload_dir['url'] . '/' . basename( $hashed_filename )
    );

    $attach_id = wp_insert_attachment( $attachment, $upload_dir['path'] . '/' . $hashed_filename );
}

I am actually struggling to link JS and PHP

//This function is called when add to cart or purchase button are pressed 
function apicrpr(state) {
//This read form values to use is later in the API request

  var longueur = document.getElementById("longueure").value,
    largeur = document.getElementById("largeure").value,
    épaisseur = document.getElementById("épaisseur").value,
    quantité = document.getElementById("quantité").value,
    matériaux = document.getElementById("matériaux").value,
    mac = document.getElementById("matériaux"),
    macval = mac.options[mac.selectedIndex].text,
    final = document.getElementById("prxxx").innerHTML,
    finalp = parseFloat(final.match(/\d+(?:\.\d+)?/g));

//Return my base 64 image as displayed in the JSON above 
    var canvas = takeshot();

//Create request 
    if (window.XMLHttpRequest){
         xmlhttp = new XMLHttpRequest();
     }

    else{
         xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
     }
//The actual url of the PHP code written above 
     var PageToSendTo = "https://websiteadress.com/wp-includes/uploadimg.php?";
     var MyVariable = canvas;
     var VariablePlaceholder = "base64_img=";
     var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable + "&title=Product_Image";
//I would like my PHP code to execute an get the url of my image back but I'm kinda lost here 
     xmlhttp.open("POST", UrlToSend, false);
     xmlhttp.send();

I hope I had been clear enough Thank you so much in advance for your help



Solution 1:[1]

You can make communication between js & php using cookies.using expiry date of cookies you can determine when data will be vanished

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Prince Hamza