0

Making use of the addImageToMediaGallery method against a Product, I am attempting to upload an image from our application to Magento.

The image is successfully being created on the server but the image is not being linked to the product using the PHP:

<?php

include_once '../../app/Mage.php';

try {

  Mage::app();

  $product = Mage::getModel('catalog/product')->load($_POST["product_id"]);
  $product->setStoreId($_POST["store_id"]);
  $bytes = base64_decode($_POST["image_bytes"]);

  $importDir = "Upload/" . $_POST["label"];
  $output = fopen($importDir, wb);
  fwrite($output, $bytes);
  fclose($output);

  if (file_exists($importDir) ) {

    $media = array();

    if ($_POST["is_thumbnail"] == "1") {
      array_push($media, 'thumbnail');
    }

    if ($_POST["is_small"] == "1") {
      array_push($media, 'small_image');
    }

    if ($_POST["is_base"] == "1") {
      array_push($media, 'image');
    }

    foreach ($media as $imageType) {
      if (file_exists($importDir)) {
        $product->addImageToMediaGallery($importDir, $imageType, false);
      }
    }

  } else {
    echo "Uploaded image not found at $importDir";
  }

  echo "true";

} catch(Exception $e) {
  Mage::logException($e);
  echo 'Message: ' .$e->getMessage();
}
?>

Any help would be appriecated

1 Answer 1

0

I needed to add a save call once the addImageToMediaGallery method had been called after the foreach loop iteration had completed.

Simply added in the following:

foreach ($media as $imageType) {
  if (file_exists($importDir)) {
    $product->addImageToMediaGallery($importDir, $imageType, false);
  }
}

**$product->save();**

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.